YADI, part 2: a simple Psyco decorator

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

[...]

[tziade@Tarek Desktop]$ python psycote.py
psycoed: 0.249526 s
not psycoed: 14.255591 s

Important announcement: Join the Nuxeo team and contribute to the Nuxeo project! We have open positions in France and the UK for open source Java EE developers and sales engineers, both junior and senior.

Like this post? Share it:


Trackback Pings

Trackback URL for this entry:
http://blogs.nuxeo.com/sections/blogs/tarek_ziade/2005_09_24_yadi-part-2-simple-psyco-decorator/tbping
Posted by Tarek Ziadé @ 09/24/2005 11:14 PM. - Categories: python -  0 comments

Nuxeo Bloggers: Log in!
Nuxeo - Indesko - Nuxeo 5 Project
All content is copyrighted by their author.
CPSSkins is Copyright © 2003-2006 by Jean-Marc Orliaguet. | CPS is Copyright © 2002-2006 by Nuxeo SAS.