Enhancing Performance

Cython (Writing C extensions for pandas)

For many use cases writing pandas in pure python and numpy is sufficient. In some computationally heavy applications however, it can be possible to achieve sizeable speed-ups by offloading work to cython.

This tutorial assumes you have refactored as much as possible in python, for example trying to remove for loops and making use of numpy vectorization, it’s always worth optimising in python first.

This tutorial walks through a “typical” process of cythonizing a slow computation. We use an example from the cython documentation but in the context of pandas. Our final cythonized solution is around 100 times faster than the pure python.

Pure python

We have a DataFrame to which we want to apply a function row-wise.

In [1]: df = DataFrame({'a': randn(1000), 'b': randn(1000),'N': randint(100, 1000, (1000)), 'x': 'x'})

In [2]: df

<class 'pandas.core.frame.DataFrame'>
Int64Index: 1000 entries, 0 to 999
Data columns (total 4 columns):
N    1000  non-null values
a    1000  non-null values
b    1000  non-null values
x    1000  non-null values
dtypes: float64(2), int64(1), object(1)

Here’s the function in pure python:

In [3]: def f(x):
   ...:     return x * (x - 1)
   ...: 

In [4]: def integrate_f(a, b, N):
   ...:     s = 0
   ...:     dx = (b - a) / N
   ...:     for i in range(N):
   ...:         s += f(a + i * dx)
   ...:     return s * dx
   ...: 

We achieve our result by by using apply (row-wise):

In [5]: %timeit df.apply(lambda x: integrate_f(x['a'], x['b'], x['N']), axis=1)
1 loops, best of 3: 219 ms per loop

But clearly this isn’t fast enough for us. Let’s take a look and see where the time is spent during this operation (limited to the most time consuming four calls) using the prun ipython magic function:

In [6]: %prun -l 4 df.apply(lambda x: integrate_f(x['a'], x['b'], x['N']), axis=1)
         573595 function calls in 0.334 seconds
   Ordered by: internal time
   List reduced from 79 to 4 due to restriction <4>
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1000    0.195    0.000    0.307    0.000 <ipython-input-4-a877a66f40a5>:1(integrate_f)
   552423    0.107    0.000    0.107    0.000 <ipython-input-3-0b27f90c4c8a>:1(f)
     1000    0.005    0.000    0.005    0.000 {range}
     1000    0.003    0.000    0.009    0.000 series.py:501(from_array)

By far the majority of time is spend inside either integrate_f or f, hence we’ll concentrate our efforts cythonizing these two functions.

Note

In python 2 replacing the range with its generator counterpart (xrange) would mean the range line would vanish. In python 3 range is already a generator.

Plain cython

First we’re going to need to import the cython magic function to ipython:

In [7]: %load_ext cythonmagic

Now, let’s simply copy our functions over to cython as is (the suffix is here to distinguish between function versions):

In [8]: %%cython
   ...: def f_plain(x):
   ...:     return x * (x - 1)
   ...: def integrate_f_plain(a, b, N):
   ...:     s = 0
   ...:     dx = (b - a) / N
   ...:     for i in range(N):
   ...:         s += f_plain(a + i * dx)
   ...:     return s * dx
   ...: 

Note

If you’re having trouble pasting the above into your ipython, you may need to be using bleeding edge ipython for paste to play well with cell magics.

In [9]: %timeit df.apply(lambda x: integrate_f_plain(x['a'], x['b'], x['N']), axis=1)
10 loops, best of 3: 117 ms per loop

Already this has shaved a third off, not too bad for a simple copy and paste.

Adding type

We get another huge improvement simply by providing type information:

In [10]: %%cython
   ....: cdef double f_typed(double x) except? -2:
   ....:     return x * (x - 1)
   ....: cpdef double integrate_f_typed(double a, double b, int N):
   ....:     cdef int i
   ....:     cdef double s, dx
   ....:     s = 0
   ....:     dx = (b - a) / N
   ....:     for i in range(N):
   ....:         s += f_typed(a + i * dx)
   ....:     return s * dx
   ....: 
In [11]: %timeit df.apply(lambda x: integrate_f_typed(x['a'], x['b'], x['N']), axis=1)
10 loops, best of 3: 19.2 ms per loop

Now, we’re talking! It’s now over ten times faster than the original python implementation, and we haven’t really modified the code. Let’s have another look at what’s eating up time:

In [12]: %prun -l 4 df.apply(lambda x: integrate_f_typed(x['a'], x['b'], x['N']), axis=1)
         20172 function calls in 0.027 seconds
   Ordered by: internal time
   List reduced from 77 to 4 due to restriction <4>
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
     1000    0.003    0.000    0.009    0.000 series.py:501(from_array)
     1001    0.002    0.000    0.011    0.000 frame.py:4457(<genexpr>)
        1    0.002    0.002    0.027    0.027 frame.py:4433(_apply_standard)
     3000    0.002    0.000    0.004    0.000 index.py:718(get_value)

Using ndarray

It’s calling series... a lot! It’s creating a Series from each row, and get-ting from both the index and the series (three times for each row). Function calls are expensive in python, so maybe we could minimise these by cythonizing the apply part.

Note

We are now passing ndarrays into the cython function, fortunately cython plays very nicely with numpy.

In [13]: %%cython
   ....: cimport numpy as np
   ....: import numpy as np
   ....: cdef double f_typed(double x) except? -2:
   ....:     return x * (x - 1)
   ....: cpdef double integrate_f_typed(double a, double b, int N):
   ....:     cdef int i
   ....:     cdef double s, dx
   ....:     s = 0
   ....:     dx = (b - a) / N
   ....:     for i in range(N):
   ....:         s += f_typed(a + i * dx)
   ....:     return s * dx
   ....: cpdef np.ndarray[double] apply_integrate_f(np.ndarray col_a, np.ndarray col_b, np.ndarray col_N):
   ....:     assert (col_a.dtype == np.float and col_b.dtype == np.float and col_N.dtype == np.int)
   ....:     cdef Py_ssize_t i, n = len(col_N)
   ....:     assert (len(col_a) == len(col_b) == n)
   ....:     cdef np.ndarray[double] res = np.empty(n)
   ....:     for i in range(len(col_a)):
   ....:         res[i] = integrate_f_typed(col_a[i], col_b[i], col_N[i])
   ....:     return res
   ....: 

The implementation is simple, it creates an array of zeros and loops over the rows, applying our integrate_f_typed, and putting this in the zeros array.

Note

Loop like this would be extremely slow in python, but in cython looping over numpy arrays is fast.

In [14]: %timeit apply_integrate_f(df['a'], df['b'], df['N'])
100 loops, best of 3: 6.69 ms per loop

We’ve gone another three times faster! Let’s check again where the time is spent:

In [15]: %prun -l 4 apply_integrate_f(df['a'], df['b'], df['N'])
         9036 function calls in 0.010 seconds
   Ordered by: internal time
   List reduced from 13 to 4 due to restriction <4>
   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.004    0.004    0.010    0.010 {_cython_magic_e90d139b668b225d575329a3043b5155.apply_integrate_f}
     3000    0.002    0.000    0.004    0.000 index.py:718(get_value)
     3000    0.002    0.000    0.006    0.000 series.py:616(__getitem__)
     3000    0.001    0.000    0.001    0.000 {method 'get_value' of 'pandas.index.IndexEngine' objects}

As one might expect, the majority of the time is now spent in apply_integrate_f, so if we wanted to make anymore efficiencies we must continue to concentrate our efforts here.

More advanced techniques

There is still scope for improvement, here’s an example of using some more advanced cython techniques:

In [16]: %%cython
   ....: cimport cython
   ....: cimport numpy as np
   ....: import numpy as np
   ....: cdef double f_typed(double x) except? -2:
   ....:     return x * (x - 1)
   ....: cpdef double integrate_f_typed(double a, double b, int N):
   ....:     cdef int i
   ....:     cdef double s, dx
   ....:     s = 0
   ....:     dx = (b - a) / N
   ....:     for i in range(N):
   ....:         s += f_typed(a + i * dx)
   ....:     return s * dx
   ....: @cython.boundscheck(False)
   ....: @cython.wraparound(False)
   ....: cpdef np.ndarray[double] apply_integrate_f_wrap(np.ndarray[double] col_a, np.ndarray[double] col_b, np.ndarray[Py_ssize_t] col_N):
   ....:     cdef Py_ssize_t i, n = len(col_N)
   ....:     assert len(col_a) == len(col_b) == n
   ....:     cdef np.ndarray[double] res = np.empty(n)
   ....:     for i in range(n):
   ....:         res[i] = integrate_f_typed(col_a[i], col_b[i], col_N[i])
   ....:     return res
   ....: 
In [17]: %timeit apply_integrate_f_wrap(df['a'], df['b'], df['N'])
100 loops, best of 3: 2.14 ms per loop

This shaves another third off!

Further topics

  • Loading C modules into cython.

Read more in the cython docs.