Deutsch Open-Source Weblog Resources zopyx group Imprint

Python, Zope, Plone — Development and Consulting

What can we do for you?

Your contact
Andreas Jung will assist you. Please call
+49(0)70 71/79 33 76

Or use our Callback service

A Python decorator for measuring the execution time of methods

— abgelegt unter:

As Python developer you often have the need for profiling and benchmarking applications. The standard tools are the Python profiler hotshot or standard debugging code with timestamp. Within one of our current project I had to track down performance issues related to LDAP connectivity. The goal was to measure the time spend within the connect() and search() method of the LDAPUserFolder implementation. As result I wrote a small @timeit decorator that allows you to measure the execution times of dedicated methods (module-level methods or class methods) by just adding the @timeit decorator in in front of the method call.

import time                                                

def timeit(method):

    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()

        print '%r (%r, %r) %2.2f sec' % \
              (method.__name__, args, kw, te-ts)
        return result

    return timed

class Foo(object):

    @timeit
    def foo(self, a=2, b=3):
        time.sleep(0.2)

@timeit
def f1():
    time.sleep(1)
    print 'f1'

@timeit
def f2(a):
    time.sleep(2)
    print 'f2',a

@timeit
def f3(a, *args, **kw):
    time.sleep(0.3)
    print 'f3', args, kw

f1()
f2(42)
f3(42, 43, foo=2)
Foo().foo()

Update:

There is also the profilehooks module by Marius Gedminas basically doing something similar (in detail: it profiles the hooked method). It is perhaps the better alternative.

Artikelaktionen

Testimonial

Andreas Jung held a two-day hands-on training and workshop in our company. Due to his large knowledge in Zope we were able to proceed with our project faster and more efficient. He could answer all questions in details or delivered solutions to open problems immediately after the workshop. This laid the foundation for a good cooperation in the future.

Walter Streicher, Project leader, BG-Phoenics, Munich

 
ZOPYX Ltd., Charlottenstr. 37/1, D-72070 Tübingen, Germany
Phone +49(0)70 71/79 33 76, Fax +49(0)70 71/7 93 68 40, Email: info@zopyx.com
Contact form Callback service Print page