Cython & C++: Why It Is Worth It

In this notebook, I demo why I spent the time to write Cython and C++ code.


In [3]:
# import custom modules
import py_video_segment as pvs
import numpy as np

In [6]:
# Define python function to get the number of false positives
def PyNumberFalsePositives(truth, predicted):
    count = 0; 
    for i in predicted: 
        if not((i in truth)): 
            count = count + 1; 
    return count

truth = np.array([1, 2, 3, 9, 10, 11]); 
predicted = np.array([4, 5, 6, 7, 8]); 

length = 100;

In [7]:
%timeit PyNumberFalsePositives(truth, predicted)


100000 loops, best of 3: 19.4 µs per loop

In [8]:
ma = pvs.PyMethodAccuracy(truth, predicted, 10)
%timeit ma.NumFalsePositives()


Created PyMethodAccuracy
Size is : 6
Size is : 5
The slowest run took 14.10 times longer than the fastest. This could mean that an intermediate result is being cached 
10000000 loops, best of 3: 142 ns per loop

Analysis

As you can see, we are running significantly faster with the compiled code. 142 ns vs 19.4 micro seconds per loop. That is a 33x speed up for the same algorithm. Thus it is key to implement bottleneck code at the C++/Cython level.