cython/cython

Integrate test from quickstart.

1 parent 0cc67f9 commit f9a1e09b46b9153db294fa888d7b56b1a52ef8d8 robertwb committed Jun 9, 2011
Showing with 42 additions and 1 deletion.
1. +9 −0 Demos/integrate0.py
2. +9 −0 Demos/integrate1.pyx
3. +10 −0 Demos/integrate2.pyx
4. +13 −0 Demos/integrate_timing.py
5. +1 −1 docs/src/quickstart/cythonize.rst
 @@ -0,0 +1,9 @@ +def f(x): + return x**2-x + +def integrate_f(a, b, N): + s = 0.0 + dx = (b-a)/N + for i in range(N): + s += f(a+i*dx) + return s * dx
 @@ -0,0 +1,9 @@ +def f(x): + return x**2-x + +def integrate_f(a, b, N): + s = 0.0 + dx = (b-a)/N + for i in range(N): + s += f(a+i*dx) + return s * dx
 @@ -0,0 +1,10 @@ +cdef double f(double x): except? -2: + return x**2-x + +def integrate_f(double a, double b, int N): + cdef int i + s = 0.0 + dx = (b-a)/N + for i in range(N): + s += f(a+i*dx) + return s * dx
 @@ -0,0 +1,13 @@ +import timeit + +import integrate0, integrate1, integrate2 + +number = 10 +py_time = None +for m in ('integrate0', 'integrate1', 'integrate2'): + print m + t = min(timeit.repeat("integrate_f(0.0, 10.0, 10000000)", "from %s import integrate_f" % m, number=number)) + if py_time is None: + py_time = t + print " ", t / number, "s" + print " ", py_time / t
 @@ -80,7 +80,7 @@ argument in order to pass it. Therefore Cython provides a syntax for declaring a C-style function, the cdef keyword:: - cdef double f(double) except? -2: + cdef double f(double x) except? -2: return x**2-x Some form of except-modifier should usually be added, otherwise Cython