How to make python faster?

高洛峰
Release: 2016-10-18 14:36:20
Original
1381 people have browsed it

Python and other scripting languages ​​are often abandoned because they are inefficient compared to compiled languages ​​like C. For example, the following example of Fibonacci numbers:

In C language:

int fib(int n){
   if (n < 2)
     return n;
   else
     return fib(n - 1) + fib(n - 2);
}
int main() {
    fib(40);
    return 0;
Copy after login

In Python:

def fib(n):
  if n < 2:
     return n
  else:
     return fib(n - 1) + fib(n - 2)
fib(40)
Copy after login

Here are their respective execution times:

$ time ./fib
3.099s
  
$ time python fib.py
16.655s
Copy after login

As expected, the C language execution in this example The efficiency is 5 times faster than Python.


In the case of web scraping, execution speed is not very important because the bottleneck is I/O - downloading the web page. But I also want to use Python in other environments, so let's take a look at how to improve the execution speed of python.


First we install a python module: psyco. The installation is very simple. You only need to execute the following command:

sudo apt-get install python-psyco
Copy after login

Or if you are on centos, execute:

sudo yum install python-psyco
Copy after login

Then let’s verify it:

#引入psyco模块,author: www.pythontab.com
import psyco
psyco.full()
def fib(n):
  if n < 2:
     return n
  else:
     return fib(n - 1) + fib(n - 2)
fib(40)
Copy after login

Haha , witness the miraculous moment! !

$ time python fib.py
3.190s
Copy after login

It only took 3 seconds. After using the psyco module, python runs as fast as C!


Now I add the following code to almost most of my python codes to enjoy the speed improvement brought by psyco

try:
    import psyco
    psyco.full()
except ImportError:
    pass # psyco not installed so continue as usual
Copy after login


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template