This article mainly introduces how to use the Psyco module in Python to optimize the running speed. the Psyco module allows your Python program to run as fast as the C language. This article provides multiple code examples, I also explained how to install and use Psyco. if you need it, you can refer to the introduction of the Psyco module today. the Psyco module allows your Python program to run as fast as the C language.
Python is easy to learn, but its performance is much inferior to that of some compilation languages (such as C). here, you can use C and Python to compile the Fibonacci series computing program, and calculate the running time:
C language program
The code is as follows:
Int fib (int n ){
If (n <2)
Return n;
Else
Return fib (n-1) + fib (n-2 );
}
Int main (){
Fib (40 );
Return 0;
}
Written in Python
The code is as follows:
Def fib (n ):
If n <2:
Return n
Else:
Return fib (n-1) + fib (n-2)
Fib (40)
Running time
The code is as follows:
$ Time./fib
3.099 s
$ Time python fib. py
16.655 s
We can see that the running time is still a little different. The difference here is about five times. now we will introduce Psyco:
Psyco is an extension module of the Python language. it can perform professional algorithm optimization on program code in real time and improve the program execution speed to a certain extent, especially when the program has a large number of cyclic operations. It was first developed by Armin Rigo and subsequently maintained and improved by Christian Tismer.
Psyco can run on 32-bit GNU/Linux, BSD, Mac OS X, and Microsoft Windows platforms. Psyco is written in C language and only coded for the 32-bit platform. Development has been stopped and replaced by PyPy. PyPy also provides support for 64-bit systems. Psyco can be automatically optimized when the Python interpreter compiles the code. it is implemented using C and some special optimizations are made for loop operations. After these optimizations, the program performance will be improved, especially in cross-platform environments.
Install Psyco
The code is as follows:
Sudo apt-get install python-psyco
You can also download the installation package from the official website and install it with easy install.
Use the Psyco module
The code is as follows:
Import psyco
Psyco. full ()
Def fib (n ):
If n <2:
Return n
Else:
Return fib (n-1) + fib (n-2)
Fib (40)
Running result
The code is as follows:
$ Time python fib. py
3.190 s
Improve your code
Now I add the following scripts to most of my Python code to use Psyco to increase the running speed:
The code is as follows:
Try:
Import psyco
Psyco. full ()
Failed T ImportError:
Pass # psyco not installed so continue as usual