Today introduces the Psyco module, which can make your Python program run as fast as C.
It is said that the Python language is easy to use and easy to learn, but the performance with some compiled languages (such as C) to compare a lot worse, here you can use C and Python language each write Fibonacci series calculation program, and calculate the running time:
C program
int fib(int n){
if (n < 2)
return n;
else
return fib(n - 1) + fib(n - 2);
}
int main() {
fib(40);
return 0;
}
Python.
def fib(n):
if n < 2:
return n
else:
return fib(n - 1) + fib(n - 2)
fib(40)
running time
$ time ./fib
3.099s
$ time python
16.655s
As you can see there is still a bit of a difference in the runtime, here the difference is about 5x or so, now on to Psyco:
Psyco is an extension module for the Python language that allows on-the-fly professional algorithmic optimization of program code, which can increase the execution speed of programs to a certain extent, especially when there are a lot of loops in the program. It was first developed by Armin Rigo, and later maintained and refined by Christian Tismer.
Psyco runs on 32-bit GNU/Linux, BSD, Mac OS X, and Microsoft Windows platforms, and is written in C and coded for 32-bit platforms only. Psyco has been discontinued and replaced by PyPy, which also provides support for 64-bit systems. Psyco can be automatically optimized when the Python interpreter compiles the code, implementing it in C and making some special optimizations for loops. As a result of these optimizations, the performance of your program will improve, especially in a cross-platform environment.
Installing Psyco
sudo apt-get install python-psyco
Or go to the official website to download the installation package, use easy install to install.
Using the Psyco module
import psyco
()
def fib(n):
if n < 2:
return n
else:
return fib(n - 1) + fib(n - 2)
fib(40)
running result
$ time python
3.190s
Improve your code
Now take most of my Python code and add the following script to speed things up with Psyco:
try:
import psyco
()
except ImportError:
pass # psyco not installed so continue as usual