Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Project: math480-2016
Views: 2158

Cython

A Very Brief Introduction!

Cython website: http://cython.org/

And a mailing list thread from today: https://groups.google.com/forum/#!topic/cython-users/7zlP_j5Rd7w

# recall def sin_sum(m): return sum(math.sin(i) for i in xrange(m))
%timeit sin_sum(10000)
125 loops, best of 3: 2.12 ms per loop
%cython import math def sin_sum_cython0(m): return sum(math.sin(i) for i in xrange(m))
Defined math, sin_sum_cython0
Auto-generated code...
%timeit sin_sum_cython0(10000)
125 loops, best of 3: 1.5 ms per loop
# not that impressive... but *typical* 2.12/1.5
1.41333333333333

Talk about type declaration and direct calling of C code...

%cython cdef extern from "math.h": cdef double sin(double) def sin_sum_cython(int m): cdef double s = 0 cdef int k for k in range(m): s += sin(k) return s
Defined sin_sum_cython
Auto-generated code...
%timeit sin_sum_cython(10000)
625 loops, best of 3: 472 µs per loop
2.12/.472
4.49152542372881
def sin_sum0(m): return float(sum(sin(i) for i in xrange(m)))
%time sin_sum0(10000)
1.9395054106807317 CPU time: 3.88 s, Wall time: 3.94 s
# speedup over original: 10000x 3.94/.000397
9924.43324937028

You probably can't beat this by much without a new idea...