Using Psyco to implement python execution speed to the same level as the compiled language

  • 2020-04-02 14:14:00
  • OfStack

This article is an example of how to use Psyco to improve the execution speed of python to the same level as the compiled language. The specific implementation method is as follows:

Install Psyco Very simple, it has two installation methods, one is the source method, one is the binary code method:

To install it source-style, you need to compile the psyco subdirectory in the source directory by calling the python setup.py install command, and then copy the entire subdirectory into python's site-packages directory.

If installed in binary code, download the appropriate binaries according to the python and psyco versions corresponding table in the list of urls, and after unzipping, a directory of psyco-1.x will be generated. Just copy the entire psyco directory into python's site-packages directory.

Ii. Instructions for use , insert the following two sentences in front of the source files that need to be optimized for efficiency:

import psyco
psyco.full()

In addition, you can use psyco.profile() to properly analyze large programs to determine which functions are best worth compiling.
The psyco.log() function is used to record the information from the profile(), so you can run it faster next time.
Psyco.bind (myfunc) specifies that the function myfunc is compiled for finer control than full().
Psyco.proxy (f) creates a new function whose code is compiled by f into binary code

Iii. Examples:
The file code of psyco_test.py is as follows:

#!/usr/bin/python
# Filename:psyco_test.py
 
import math, timeit, psyco
 
def TestA():
    res, loopcnt = 0.0, 100
    for i in range(loopcnt):
        for j in range(loopcnt):
            for k in range(loopcnt):
                res = res + math.sin(i + j + k)
 
if __name__ == '__main__':
    TestB = psyco.proxy(TestA)
    ta = timeit.Timer("TestA()", "from __main__ import TestA")
    tb = timeit.Timer("TestB()", "from __main__ import TestB")
    print ("TestA(): %.2fs" % (ta.timeit(10)))
    print ("TestB(): %.2fs" % (tb.timeit(10)))

The operation results are as follows:

jobin@jobin-desktop:~/work/python/psyco$ python psyco_test.py
TestA(): 4.41s
TestB(): 1.63s

Functions treated with psyco perform about four times faster, as the authors claim.

I hope this article has helped you with your Python programming.


Related articles: