SoFunction
Updated on 2024-10-29

Optimizing Speed with the Psyco Module for Python

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

Copy Code 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;
}

Python.
Copy Code 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
Copy Code The code is as follows.

$ 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

Copy Code The code is as follows.

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

Copy Code The code is as follows.

import psyco
()
 
def fib(n):
  if n < 2:
     return n
  else:
     return fib(n - 1) + fib(n - 2)
fib(40)

running result

Copy Code The code is as follows.

$ 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:

Copy Code The code is as follows.

try: 
    import psyco 
    () 
except ImportError: 
    pass # psyco not installed so continue as usual