Psyco is a pretty cool tool from
Armin Rigo, that can really speed up the code in some cases. It relies on
generating machine code by writing the corresponding bytes directly into
executable memory.



For language lawyers and people interested in the subject, the website has
a lot of papers on how Psyco works.



But the caveats makes
it quite unusable as a  global application directive and it's better to
target the code where we want Psyco to do the speed.



Psyco comes with a handy set of API, and the proxy() function, that takes a
callable object and returns a psychoed-callable object, makes it easy to
create a decorator that can be used whenever needed.



import psyco

decorator psycoed

def psycoed(function):
try:
return psyco.proxy(function)
except TypeError:
return function


The TypeError thing just prevents errors on objets that can't be proxied.



The psyco-effect is quite cool:



def normal():
a = 0
for i in range(5000):
a = a + 3
return a
@psycoed
def speedy():
a = 0
for i in range(5000):
a = a + 3
return a
if name == 'main':
import timeit
temps = timeit.Timer('speedy()', 'from main import speedy').timeit(10000)
print 'psycoed: %f s' % temps
temps = timeit.Timer('normal()', 'from main import normal').timeit(10000)
print 'not psycoed: %f s' % temps
[...]
[[email protected] Desktop]$ python psycote.py
psycoed: 0.249526 s
not psycoed: 14.255591 s

(Post originally written by Tarek Ziadé on the old Nuxeo blogs.)