XClose
Menu

Cython

Cython can be viewed as an extension of Python where variables and functions are annotated with extra information, in particular types. The resulting Cython source code will be compiled into optimized C or C++ code, and thereby yielding substantial speed-up of slow Python code. In other words, Cython provides a way of writing Python with comparable performance to that of C/C++.

Start Coding in Cython

Cython code must, unlike Python, be compiled. This happens in the following stages:

  • The cython code in .pyx file will be translated to a C file.
  • The C file will be compiled by a C compiler into a shared library, which will be directly loaded into Python.

In a Jupyter notebook, everything is a lot easier. One needs only to load the Cython extension (%load_ext Cython) at the beginning and put %%cython mark in front of cells of Cython code. Cells with Cython mark will be treated as a .pyx code and consequently, compiled into C.

For details, please see Building Cython Code.

Pure python Mandelbrot set:

In [1]:
xmin = -1.5
ymin = -1.0
xmax = 0.5
ymax = 1.0
resolution = 300
xstep = (xmax - xmin) / resolution
ystep = (ymax - ymin) / resolution
xs = [(xmin + (xmax - xmin) * i / resolution) for i in range(resolution)]
ys = [(ymin + (ymax - ymin) * i / resolution) for i in range(resolution)]
In [2]:
def mandel(position, limit=50):
    value = position
    while abs(value) < 2:
        limit -= 1
        value = value**2 + position
        if limit < 0:
            return 0
    return limit

Compiled by Cython:

In [3]:
%load_ext Cython 
---------------------------------------------------------------------------
ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-3-5f465735d1d6> in <module>
----> 1 get_ipython().run_line_magic('load_ext', 'Cython ')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-65> in load_ext(self, module_str)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/extension.py in load_ext(self, module_str)
     31         if not module_str:
     32             raise UsageError('Missing module name.')
---> 33         res = self.shell.extension_manager.load_extension(module_str)
     34 
     35         if res == 'already loaded':

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/extensions.py in load_extension(self, module_str)
     78             if module_str not in sys.modules:
     79                 with prepended_to_syspath(self.ipython_extension_dir):
---> 80                     mod = import_module(module_str)
     81                     if mod.__file__.startswith(self.ipython_extension_dir):
     82                         print(("Loading extensions from {dir} is deprecated. "

~/virtualenv/python3.6.3/lib/python3.6/importlib/__init__.py in import_module(name, package)
    124                 break
    125             level += 1
--> 126     return _bootstrap._gcd_import(name[level:], package, level)
    127 
    128 

~/virtualenv/python3.6.3/lib/python3.6/importlib/_bootstrap.py in _gcd_import(name, package, level)

~/virtualenv/python3.6.3/lib/python3.6/importlib/_bootstrap.py in _find_and_load(name, import_)

~/virtualenv/python3.6.3/lib/python3.6/importlib/_bootstrap.py in _find_and_load_unlocked(name, import_)

ModuleNotFoundError: No module named 'Cython '
In [4]:
%%cython

def mandel_cython(position, limit=50):
    value = position
    while abs(value) < 2:
        limit -= 1
        value = value**2 + position
        if limit < 0:
            return 0
    return limit
UsageError: Cell magic `%%cython` not found.

Let's verify the result

In [5]:
from matplotlib import pyplot as plt
%matplotlib inline
f, axarr = plt.subplots(1, 2)
axarr[0].imshow([[mandel(complex(x, y)) for x in xs] for y in ys], interpolation='none')
axarr[0].set_title('Pure Python')
axarr[1].imshow([[mandel_cython(complex(x, y)) for x in xs] for y in ys], interpolation='none')
axarr[1].set_title('Cython')
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-5-7570640dcfd5> in <module>
      4 axarr[0].imshow([[mandel(complex(x, y)) for x in xs] for y in ys], interpolation='none')
      5 axarr[0].set_title('Pure Python')
----> 6 axarr[1].imshow([[mandel_cython(complex(x, y)) for x in xs] for y in ys], interpolation='none')
      7 axarr[1].set_title('Cython')

<ipython-input-5-7570640dcfd5> in <listcomp>(.0)
      4 axarr[0].imshow([[mandel(complex(x, y)) for x in xs] for y in ys], interpolation='none')
      5 axarr[0].set_title('Pure Python')
----> 6 axarr[1].imshow([[mandel_cython(complex(x, y)) for x in xs] for y in ys], interpolation='none')
      7 axarr[1].set_title('Cython')

<ipython-input-5-7570640dcfd5> in <listcomp>(.0)
      4 axarr[0].imshow([[mandel(complex(x, y)) for x in xs] for y in ys], interpolation='none')
      5 axarr[0].set_title('Pure Python')
----> 6 axarr[1].imshow([[mandel_cython(complex(x, y)) for x in xs] for y in ys], interpolation='none')
      7 axarr[1].set_title('Cython')

NameError: name 'mandel_cython' is not defined
In [6]:
%timeit [[mandel(complex(x,y)) for x in xs] for y in ys] # pure python
%timeit [[mandel_cython(complex(x,y)) for x in xs] for y in ys] # cython
682 ms ± 8.97 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-6-a72aaf6fe1bc> in <module>
      1 get_ipython().run_line_magic('timeit', '[[mandel(complex(x,y)) for x in xs] for y in ys] # pure python')
----> 2 get_ipython().run_line_magic('timeit', '[[mandel_cython(complex(x,y)) for x in xs] for y in ys] # cython')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-61> in timeit(self, line, cell, local_ns)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, line, cell, local_ns)
   1129             for index in range(0, 10):
   1130                 number = 10 ** index
-> 1131                 time_number = timer.timeit(number)
   1132                 if time_number >= 0.2:
   1133                     break

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:

<magic-timeit> in inner(_it, _timer)

<magic-timeit> in <listcomp>(.0)

<magic-timeit> in <listcomp>(.0)

NameError: name 'mandel_cython' is not defined

We have improved the performance of a factor of 1.5 by just using the Cython compiler, without changing the code!

Cython with C Types

But we can do better by telling Cython what C data type we would use in the code. Note we're not actually writing C, we're writing Python with C types.

typed variable

In [7]:
%%cython
def var_typed_mandel_cython(position, limit=50):
    cdef double complex value # typed variable
    value = position
    while abs(value) < 2:
        limit -= 1
        value = value**2 + position
        if limit < 0:
            return 0
    return limit
UsageError: Cell magic `%%cython` not found.

typed function + typed variable

In [8]:
%%cython
cpdef call_typed_mandel_cython(double complex position,
                               int limit=50): # typed function
    cdef double complex value # typed variable
    value = position
    while abs(value)<2:
        limit -= 1
        value = value**2 + position
        if limit < 0:
            return 0
    return limit
UsageError: Cell magic `%%cython` not found.

performance of one number:

In [9]:
# pure python
%timeit a = mandel(complex(0, 0)) 
14.2 µs ± 496 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
In [10]:
# primitive cython
%timeit a = mandel_cython(complex(0, 0)) 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-10-03d48e75f989> in <module>
      1 # primitive cython
----> 2 get_ipython().run_line_magic('timeit', 'a = mandel_cython(complex(0, 0)) ')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-61> in timeit(self, line, cell, local_ns)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, line, cell, local_ns)
   1129             for index in range(0, 10):
   1130                 number = 10 ** index
-> 1131                 time_number = timer.timeit(number)
   1132                 if time_number >= 0.2:
   1133                     break

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:

<magic-timeit> in inner(_it, _timer)

NameError: name 'mandel_cython' is not defined
In [11]:
# cython with C type variable
%timeit a = var_typed_mandel_cython(complex(0, 0)) 
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-11-01405f40d218> in <module>
      1 # cython with C type variable
----> 2 get_ipython().run_line_magic('timeit', 'a = var_typed_mandel_cython(complex(0, 0)) ')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-61> in timeit(self, line, cell, local_ns)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, line, cell, local_ns)
   1129             for index in range(0, 10):
   1130                 number = 10 ** index
-> 1131                 time_number = timer.timeit(number)
   1132                 if time_number >= 0.2:
   1133                     break

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:

<magic-timeit> in inner(_it, _timer)

NameError: name 'var_typed_mandel_cython' is not defined
In [12]:
# cython with typed variable + function
%timeit a = call_typed_mandel_cython(complex(0, 0))
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-12-001b3da907f7> in <module>
      1 # cython with typed variable + function
----> 2 get_ipython().run_line_magic('timeit', 'a = call_typed_mandel_cython(complex(0, 0))')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-61> in timeit(self, line, cell, local_ns)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, line, cell, local_ns)
   1129             for index in range(0, 10):
   1130                 number = 10 ** index
-> 1131                 time_number = timer.timeit(number)
   1132                 if time_number >= 0.2:
   1133                     break

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:

<magic-timeit> in inner(_it, _timer)

NameError: name 'call_typed_mandel_cython' is not defined

Cython with numpy ndarray

You can use NumPy from Cython exactly the same as in regular Python, but by doing so you are losing potentially high speedups because Cython has support for fast access to NumPy arrays.

In [13]:
import numpy as np
ymatrix, xmatrix = np.mgrid[ymin:ymax:ystep, xmin:xmax:xstep]
values = xmatrix + 1j * ymatrix
In [14]:
%%cython
import numpy as np
cimport numpy as np 

cpdef numpy_cython_1(np.ndarray[double complex, ndim=2] position, 
                     int limit=50): 
    cdef np.ndarray[long,ndim=2] diverged_at
    cdef double complex value
    cdef int xlim
    cdef int ylim
    cdef double complex pos
    cdef int steps
    cdef int x, y

    xlim = position.shape[1]
    ylim = position.shape[0]
    diverged_at = np.zeros([ylim, xlim], dtype=int)
    for x in xrange(xlim):
        for y in xrange(ylim):
            steps = limit
            value = position[y,x]
            pos = position[y,x]
            while abs(value) < 2 and steps >= 0:
                steps -= 1
                value = value**2 + pos
            diverged_at[y,x] = steps
  
    return diverged_at
UsageError: Cell magic `%%cython` not found.

Note the double import of numpy: the standard numpy module and a Cython-enabled version of numpy that ensures fast indexing of and other operations on arrays. Both import statements are necessary in code that uses numpy arrays. The new thing in the code above is declaration of arrays by np.ndarray.

In [15]:
%timeit data_cy = [[mandel(complex(x,y)) for x in xs] for y in ys] # pure python
708 ms ± 43 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
In [16]:
%timeit data_cy = [[call_typed_mandel_cython(complex(x,y)) for x in xs] for y in ys] # typed cython
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-16-4788bd5aaf09> in <module>
----> 1 get_ipython().run_line_magic('timeit', 'data_cy = [[call_typed_mandel_cython(complex(x,y)) for x in xs] for y in ys] # typed cython')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-61> in timeit(self, line, cell, local_ns)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, line, cell, local_ns)
   1129             for index in range(0, 10):
   1130                 number = 10 ** index
-> 1131                 time_number = timer.timeit(number)
   1132                 if time_number >= 0.2:
   1133                     break

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:

<magic-timeit> in inner(_it, _timer)

<magic-timeit> in <listcomp>(.0)

<magic-timeit> in <listcomp>(.0)

NameError: name 'call_typed_mandel_cython' is not defined
In [17]:
%timeit numpy_cython_1(values) # ndarray
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-17-7ed1a9156416> in <module>
----> 1 get_ipython().run_line_magic('timeit', 'numpy_cython_1(values) # ndarray')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-61> in timeit(self, line, cell, local_ns)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, line, cell, local_ns)
   1129             for index in range(0, 10):
   1130                 number = 10 ** index
-> 1131                 time_number = timer.timeit(number)
   1132                 if time_number >= 0.2:
   1133                     break

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:

<magic-timeit> in inner(_it, _timer)

NameError: name 'numpy_cython_1' is not defined

A trick of using np.vectorize

In [18]:
numpy_cython_2 = np.vectorize(call_typed_mandel_cython)
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-18-e65390499867> in <module>
----> 1 numpy_cython_2 = np.vectorize(call_typed_mandel_cython)

NameError: name 'call_typed_mandel_cython' is not defined
In [19]:
%timeit numpy_cython_2(values) #  vectorize
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-19-bbbacb459734> in <module>
----> 1 get_ipython().run_line_magic('timeit', 'numpy_cython_2(values) #  vectorize')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-61> in timeit(self, line, cell, local_ns)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, line, cell, local_ns)
   1129             for index in range(0, 10):
   1130                 number = 10 ** index
-> 1131                 time_number = timer.timeit(number)
   1132                 if time_number >= 0.2:
   1133                     break

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:

<magic-timeit> in inner(_it, _timer)

NameError: name 'numpy_cython_2' is not defined

Calling C functions from Cython

Example: compare sin() from Python and C library

In [20]:
%%cython
import math
cpdef py_sin():
    cdef int x
    cdef double y
    for x in range(1e7):
        y = math.sin(x)
UsageError: Cell magic `%%cython` not found.
In [21]:
%%cython
from libc.math cimport sin as csin # import from C library
cpdef c_sin():
    cdef int x
    cdef double y
    for x in range(1e7):
        y = csin(x)
UsageError: Cell magic `%%cython` not found.
In [22]:
%timeit [math.sin(i) for i in range(int(1e7))] # python
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-22-cbb3d3515fb1> in <module>
----> 1 get_ipython().run_line_magic('timeit', '[math.sin(i) for i in range(int(1e7))] # python')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-61> in timeit(self, line, cell, local_ns)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, line, cell, local_ns)
   1129             for index in range(0, 10):
   1130                 number = 10 ** index
-> 1131                 time_number = timer.timeit(number)
   1132                 if time_number >= 0.2:
   1133                     break

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:

<magic-timeit> in inner(_it, _timer)

<magic-timeit> in <listcomp>(.0)

NameError: name 'math' is not defined
In [23]:
%timeit py_sin()                                # cython call python library
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-23-412c90c89148> in <module>
----> 1 get_ipython().run_line_magic('timeit', 'py_sin()                                # cython call python library')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-61> in timeit(self, line, cell, local_ns)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, line, cell, local_ns)
   1129             for index in range(0, 10):
   1130                 number = 10 ** index
-> 1131                 time_number = timer.timeit(number)
   1132                 if time_number >= 0.2:
   1133                     break

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:

<magic-timeit> in inner(_it, _timer)

NameError: name 'py_sin' is not defined
In [24]:
%timeit c_sin()                                 # cython call C library
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-24-695e96a6fc22> in <module>
----> 1 get_ipython().run_line_magic('timeit', 'c_sin()                                 # cython call C library')

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/interactiveshell.py in run_line_magic(self, magic_name, line, _stack_depth)
   2285                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2286             with self.builtin_trap:
-> 2287                 result = fn(*args,**kwargs)
   2288             return result
   2289 

<decorator-gen-61> in timeit(self, line, cell, local_ns)

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magic.py in <lambda>(f, *a, **k)
    185     # but it's overkill for just that one bit of state.
    186     def magic_deco(arg):
--> 187         call = lambda f, *a, **k: f(*a, **k)
    188 
    189         if callable(arg):

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, line, cell, local_ns)
   1129             for index in range(0, 10):
   1130                 number = 10 ** index
-> 1131                 time_number = timer.timeit(number)
   1132                 if time_number >= 0.2:
   1133                     break

~/virtualenv/python3.6.3/lib/python3.6/site-packages/IPython/core/magics/execution.py in timeit(self, number)
    158         gc.disable()
    159         try:
--> 160             timing = self.inner(it, self.timer)
    161         finally:
    162             if gcold:

<magic-timeit> in inner(_it, _timer)

NameError: name 'c_sin' is not defined