Skip to content

Instantly share code, notes, and snippets.

@Muhammed-Abdullah-Shaikh
Created June 15, 2023 13:36
Show Gist options
  • Save Muhammed-Abdullah-Shaikh/e48b69adba8494764c4afde5bd14b618 to your computer and use it in GitHub Desktop.
Save Muhammed-Abdullah-Shaikh/e48b69adba8494764c4afde5bd14b618 to your computer and use it in GitHub Desktop.
Cython Introduction
from timeit import default_timer as timer
class benchmark(object):
def __init__(self, msg, fmt="%0.3g"):
self.msg = msg
self.fmt = fmt
def __enter__(self):
self.start = timer()
return self
def __exit__(self, *args):
t = timer() - self.start
print(("%s : " + self.fmt + " seconds") % (self.msg, t))
self.time = t
python setup.py build_ext --inplace
python test.py
def prime_finder_vanilla(amount):
primes = []
found = 0
number = 2
while found < amount:
for x in primes:
if number % x == 0:
break
else:
primes.append(number)
found += 1
number += 1
return primes
def prime_finder_optimized(int amount):
cdef int number, x, found
cdef int primes[100000]
amount = min(amount, 100000)
found = 0
number = 2
while found < amount:
for x in primes[:found]:
if number % x == 0:
break
else:
primes[found] = number
found += 1
number += 1
return_list = [p for p in primes[:found]]
return return_list
from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules=cythonize('main.pyx')
)
import main
from benchmark import benchmark
with benchmark("vanilla"):
main.prime_finder_vanilla(10000)
with benchmark("optimized"):
main.prime_finder_optimized(10000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment