iPython Cookbook - timing execution

Timing function execution using decorators

We here define a decorator that at the beginning of the execution remembers the time, and at the end of the exexution prints the time elapse. Note that this is wallclock time, not process time, so it will depend on what else is going on at that moment source

In [1]:
import time

def time_usage(func):
    def wrapper(*args, **kwargs):
        beg_ts = time.time ()
        func(*args, **kwargs)
        end_ts = time.time ()
        print("elapsed time: %f" % (end_ts - beg_ts))
    return wrapper

To always time execution of a function, just add the decorator to its definition...

In [2]:
def test():
    for i in range(0, 100000):

...and whenever the function is run it will print the time spent in it

In [3]:

elapsed time: 0.007669

Timing code segments

This function remembers the time when it is called in a closure, and returns a function that allows to read it out.

In [4]:
import time
def new_timer(id=''):
    beg_ts = time.time ()
    def finish():
        end_ts = time.time ()
        print("%s elapsed time: %f" % (id, end_ts - beg_ts))
        return end_ts - beg_ts

    return finish

The way it works is as follows

In [5]:
mytimer = new_timer('TIMERID')
for i in range(0, 100000):

TIMERID elapsed time: 0.010734

Timing snippets using timeit

For timing the execution time of snippets - eg to compare different ways of programming the same thing - there is a function called timeit in the eponymous module source

In [6]:
import timeit
timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)


In [7]:
timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)


In [8]:
timeit.timeit('"-".join(map(str, range(100)))', number=10000)


Licence and version

(c) Stefan Loesch / oditorium 2014; all rights reserved (license)

In [9]:
import sys

3.4.0 (default, Apr 11 2014, 13:05:11) 
[GCC 4.8.2]