Skip to content

Instantly share code, notes, and snippets.

@thuwarakeshm
Last active May 27, 2022 01:11
Show Gist options
  • Save thuwarakeshm/b24bb1004cb396bcf1c5fadc99b00732 to your computer and use it in GitHub Desktop.
Save thuwarakeshm/b24bb1004cb396bcf1c5fadc99b00732 to your computer and use it in GitHub Desktop.
Challanging Cython
def count_primes(n: int) -> int:
"""Returns how many prime numbers are there less than n"""
count = 0
primes = [False for i in range(n + 1)]
for i in range(2, n):
if primes[i] == False:
count += 1
j = 2
while j * i < n:
primes[j * i] = True
j += 1
print(count)
return count
import cProfile
from multiprocessing import Pool
from count_prime import count_primes
if __name__ == "__main__":
with Pool(5) as p:
cProfile.run("p.map(count_primes, [20, 25, 30, 35, 40])")
import cProfile
from count_prime import count_primes
cProfile.run("count_primes(35)")
import cProfile
from multiprocessing import Pool
def count_primes(max_num: int):
"""This function counts of prime numbers below the input value.
Input values are in thousands, ie. 40, is 40,000.
"""
count: int = 0
for num in range(max_num * 1000 + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
count += 1
print(count)
return count
if __name__ == "__main__":
with Pool(5) as p:
cProfile.run("p.map(count_primes, [20, 25, 30, 35, 40])")
import cProfile
def count_primes(max_num: int):
"""This function counts of prime numbers below the input value.
Input values are in thousands, ie. 40, is 40,000.
"""
count: int = 0
for num in range(max_num * 1000 + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
count += 1
print(count)
return count
cProfile.run("count_primes(35)")
from setuptools import setup
from Cython.Build import cythonize
setup(
ext_modules = cythonize("count_prime.pyx")
)
import cProfile
from tuplex import *
c = Context()
def count_primes(max_num: int):
"""This function counts of prime numbers below the input value.
Input values are in thousands, ie. 40, is 40,000.
"""
count: int = 0
for num in range(max_num * 1000 + 1):
if num > 1:
for i in range(2, num):
if num % i == 0:
break
else:
count += 1
print(count)
return count
cProfile.run("c.parallelize([35]).map(count_primes).collect()")
cProfile.run("c.parallelize([20, 25, 30, 35, 40]).map(count_primes).collect()")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment