In [3]:
!pip install cython


Requirement already satisfied: cython in /home/johannes/.local/share/workon/noodles/lib/python3.7/site-packages (0.29.10)

In [4]:
%load_ext Cython

In [5]:
%%cython

from libc.math cimport ceil, sqrt


cdef inline int primeQ(int n) nogil:
    """return a boolean, is the input integer a prime?"""
    if n == 2:
        return True
    cdef int max_i = <int>ceil(sqrt(n))
    cdef int i = 2
    while i <= max_i:
       if n % i == 0:
           return False
       i += 1
    return True

cpdef unsigned long sumPrimes(int n) nogil:
    """return sum of all primes less than n """
    cdef unsigned long i = 0
    cdef int x
    for x in range(2, n):
        if primeQ(x):
            i += x
    return i

In [6]:
sumPrimes(10)


Out[6]:
17

In [7]:
import noodles
import time

In [8]:
%%time

for i in range(50000, 1000000, 50000):
    print(sumPrimes(i), flush=True)


121013308
454396537
986017447
1709600813
2623031151
3709507114
5002513514
6458901531
8093723585
9914236195
11900563183
14071826345
16404679972
18910286312
21588259025
24465663438
27489818806
30689332265
34049359802
CPU times: user 1.61 s, sys: 5.49 ms, total: 1.62 s
Wall time: 1.62 s

In [9]:
%%time

@noodles.schedule
def s_sum_primes(n):
    return sumPrimes(n)

wf = noodles.gather(*map(s_sum_primes, range(50000, 1000000, 50000)))


CPU times: user 7.83 ms, sys: 0 ns, total: 7.83 ms
Wall time: 7.75 ms

In [10]:
%%time
result = noodles.run_parallel(wf, n_threads=10)
print(result)


[121013308, 454396537, 986017447, 1709600813, 2623031151, 3709507114, 5002513514, 6458901531, 8093723585, 9914236195, 11900563183, 14071826345, 16404679972, 18910286312, 21588259025, 24465663438, 27489818806, 30689332265, 34049359802]
CPU times: user 1.57 s, sys: 3.49 ms, total: 1.58 s
Wall time: 1.57 s

In [ ]: