pip install Cython
To use Cython in our notebook, we will use the IPython magic command. Magic commands start with a percent sign and provide some additional features that can enhance the workflow. Generally, there are two types of Magic commands:
The line magic is represented by a single "%", and only one line is entered for operation
The cell magic is represented by two "%"s and operates on multiple lines of input.
Let's start:
First, in order to be able to use Cython, we must run:
%load_ext Cython
Now, whenever we want to run Cython in a code cell, we must first put the following magic command into the cell:
%%cython
After completing these, you can start writing Cython code.
Compared with ordinary Python code, the speed of Cython actually depends on the code itself. For example, if you are running a computationally expensive loop with many variables, Cython will be much better than regular Python code. Recursive functions also make Cython much faster than Python.
Let us prove this with the Fibonacci sequence. Simply put, this algorithm finds the next number by adding the first two numbers. The following are possible situations in Python:
%%cython
def fibonacci(n):if n<0:print("1st fibonacci number= 0")
elif n==1:return0
elif n==2:return1else:returnfibonacci(n-1)+fibonacci(n-2)
Run the code:
%%time
fibonacci(39)
result:
CPU times: user 8.39 s, sys:78.6 ms, total:8.47 s
Wall time:8.43 s
39088169
As you can see, it took 8.39 seconds to find the 39th digit in the sequence, where Wall time refers to the total time taken from the start to the end of the function call.
Next, what is the difference between adding -a to the magic command line:
%%cython -a
def fibonacci_c(int n):if n<0:print("1st fibonacci number = 0")
elif n==1:return0
elif n==2:return1else:returnfibonacci_c(n-1)+fibonacci_c(n-2)
The results are as follows:
As you can see, by adding '-a' after the magic command, we received some comments that show us how much Python interaction is in the code.
The goal here is to remove all the yellow lines and make them have a white background. In this case, there will be no Python interaction, and all code will run in C.
You can also click the "+" sign next to each line to view the C conversion of the Python code.
Run the code to see how fast it can be:
%%time
fibonacci_c(39)
The results are as follows:
CPU times: user 4.85 s, sys:49.7 ms, total:4.9 s
Wall time:4.89 s
39088169
In this example, Cython is about 5.8 times faster than Python. This clearly demonstrates the ability to save time with Cython, which provides the greatest improvement compared to regular Python code.
Recommended Posts