Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download
Views: 16658

Cython

A Very Brief Introduction!

Cython is a variant of Python which can be compiled directly to C. If used judiciously, this can be used to make certain code much faster with very little effort on your part.

Cython website: http://cython.org/

# recall import math def sin_sum(m): return sum(math.sin(i) for i in xrange(m))
print sin_sum(10000)
1.93950541068
%timeit sin_sum(10000)
125 loops, best of 3: 3.74 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)
625 loops, best of 3: 2.2 ms per loop
# not that impressive... but *typical* 3.74/2.2
1.70000000000000

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: 434 µs per loop
2.2/.434
5.06912442396313
def sin_sum0(m): return float(sum(sin(i) for i in xrange(m)))
%time sin_sum0(10000)
1.939505410680705 CPU time: 3.34 s, Wall time: 4.56 s
# speedup over original: 10000x 3.34/.000434
7695.85253456221

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

Aside: you might wonder why the Cythonization process couldn't be incorporated directly into the Python interpreter, so that code is automatically fast while still being easy to read and write. This is the design principle behind a closely related language called Julia, which is also available within SageMathCloud but is much newer (and hence less established) than Python.