Profiling Cython code
We will profile Cython and NumPy code that tries to approximate the Euler constant. You can refer to http://en.wikipedia.org/wiki/E_%28mathematical_constant%29 for the required formula.
How to do it...
This section demonstrates how to profile Cython code. To do this, go through the following steps:
NumPy approximation of e: For the NumPy approximation of e perform the following steps:
First, we will create an array of 1 to n (n is 40 in our example).
Then, we will compute the cumulative product of this array, which happens to be the factorial.
After that, we take the reciprocal of the factorials.
Finally, we apply the formula from the Wikipedia page. At the end, we put standard profiling code, giving us the following program:
import numpy import cProfile import pstats def approx_e(n=40): # array of [1, 2, ... n-1] arr = numpy.arange(1, n) # calculate the factorials and convert to floats arr = arr.cumprod().astype(float) # reciprocal 1/n arr = numpy.reciprocal...