Cython: Difference between revisions

Content deleted Content added
Scoder (talk | contribs)
the previous code didn't work because %load_ext Cython needs to be in a separate istruction/cell and %%cython need to be the first instruction of a new cell
Line 129:
== Using in Jupyter notebook ==
 
A more straightforward way to start with Cython is through command-line [[IPython]] (or through in-browser python console called Jupyter [[notebook interface|notebook]] (or through command-line [[IPython]]):
 
<source lang="Python">
In [1]: %load_ext Cython
def f(n):
In [2]: %%cython
a = 0
for i in range cpdef g(int n):
cdef int a += 0, i
for i in range(n):
return a
a += i
return a
a = 0
def f(n):
cdef int a = 0, i
for i in range(n):
a += i
return a
In [3]: %timeit f(1000000)
42.7 ms ± 783 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
In [4]: %timeit g(1000000)
74 µs ± 16.6 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
 
%load_ext Cython
 
%%cython
cpdef g(int n):
cdef int a = 0, i
for i in range(n):
a += i
return a
 
%timeit f(1000000)
10 loops, best of 3: 82.4 ms per loop
 
%timeit g(1000000)
1000 loops, best of 3: 314 µs per loop
</source>
 
which gives a 262585 times improvement over the pure-python version. More details on the subject in the official quickstart page.<ref>{{Cite web|url=http://cython.readthedocs.io/en/latest/src/quickstart/build.html|title=Building Cython code|website=cython.readthedocs.io|access-date=2017-04-24}}</ref>
 
== Uses ==