Aug 6, 2012

Python: simple recipe to measure your function's execution time

We always write something unusual while doing basic things. Our own bicycles and crutches to work out some unusual situation. Here is another recipe to do a thing like so. I have tried several libraries and readymade decisions. But it assumes you have them installed. And you often try things in console, don't you?

Anyway the recipe is simple and quite straightforward.

import datetime

# Getting first timestamp
t1 = datetime.datetime.now()
# Your function e.g.:
data = [g.name for g in request.user.groups.all()]
# Second timestamp
t2 = datetime.datetime.now()

print "Execution time: %s" % (t1-t2)

It is rude and quite simple but may often suit you well to measure execution time in a simple and straightforward manner.
Also nice idea to write down this function into logs. It may be handy on refactoring of your core app for e.g.;

import datetime
import logging
log = logging.getLogger('mylogger')

# Getting first timestamp
t1 = datetime.datetime.now()
# Your function e.g.:
data = [g.name for g in request.user.groups.all()]
# Second timestamp
t2 = datetime.datetime.now()
# Using Logging to write down calls
log.debug("my_function Execution time: %s" % (t1-t2))

This also can grow up to Django decorator that can log time of function execution into console/log file/whatever. But it's quite another story.
Those snippets are quite Django based. But, I think, the core is pure python, if you've got the core concept of this.

Used, have thoughts, know how to do it in a better/simpler manner? I'm wrong? Please comment!