Created
June 15, 2023 13:36
-
-
Save Muhammed-Abdullah-Shaikh/e48b69adba8494764c4afde5bd14b618 to your computer and use it in GitHub Desktop.
Cython Introduction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
python setup.py build_ext --inplace | |
python test.py |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from setuptools import setup | |
from Cython.Build import cythonize | |
setup( | |
ext_modules=cythonize('main.pyx') | |
) | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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