Contact
CoCalc Logo Icon
StoreFeaturesDocsShareSupport News AboutSign UpSign In
| Download

Cython demo

Project: Cython demo
Views: 110
Kernel: Python 2 (SageMath)

Some quick contrived Hello Maths! code examples in Python and Cython to show how Cython can speed up Python code.

iters=1000 n=10000
def pmaxsqrt(n): maxsofar = 0.0 from math import sqrt for a in range(n): x=sqrt(a) if x > maxsofar: maxsofar = x return maxsofar def pfun(n,iters): import timeit nstr=str(n) return timeit.timeit('pmaxsqrt('+nstr+')', number=iters, setup='from __main__ import pmaxsqrt')
pfun(n,iters)
1.1704959869384766
%load_ext Cython
%%cython cpdef cmaxsqrt(n): maxsofar = 0.0 from math import sqrt for a in range(n): x=sqrt(a) if x > maxsofar: maxsofar = x return maxsofar def cfun(n,iters): import timeit nstr=str(n) return timeit.timeit('cmaxsqrt('+nstr+')', number=iters, setup='from __main__ import cmaxsqrt')
cfun(n,iters)
0.6352179050445557
%%cython cpdef tmaxsqrt(int n): cdef double x cdef double maxsofar = 0.0 from math import sqrt for a in range(n): x=sqrt(a) if x > maxsofar: maxsofar = x return maxsofar def tfun(n,iters): import timeit nstr=str(n) return timeit.timeit('tmaxsqrt('+nstr+')', number=iters, setup='from __main__ import tmaxsqrt')
tfun(n,iters)
0.4050180912017822