Welcome, guest | Sign In | My Account | Store | Cart

The timeit module (in Python standard library) is handy to find out how fast a statement takes to execute, but not very convenient to compare speed of several equivalent statements: too much typing, need to create a Timer object for each statement, etc, tedious. The timings module provides the times() function to make it super easy to compare several statements in one call.

Python, 29 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from timeit import Timer

class Timing:
    def __init__(self, name, num, init, statement):
        self.__timer = Timer(statement, init)
        self.__num   = num
        self.name    = name
        self.statement = statement
        self.__result  = None
        
    def timeit(self):
        self.__result = self.__timer.timeit(self.__num)
        
    def getResult(self):
        return self.__result
        
        
def times(num=1000000, reverse=False, init='', **statements):
    # time each statement
    timings = []
    for n, s in statements.iteritems():
        t = Timing(n, num, init, s)
        t.timeit()
        timings.append(t)
    
    # print results
    timings.sort(key=Timing.getResult, reverse=reverse)
    for t in timings:
        print "%s => %.3f s" % (t.name, t.getResult())

Arguments to the times() function: - num is the number of times that each statement will be executed (see first argument in the timeit.Timer.timeit() method in Python docs); - The init statement is executed only once for each statement and is not part of the timing results. The init typically initializes some locals used in the statements (see timeit.Timer class); - The **statements kwarg is a dict of statements to be timed, where key is a 'name' to refer to the statement in results printout, and value is the statement (as a string).

Prints the timings from smallest to largest (unless reverse=True, then opposite).

E.g.

times(init='l=range(1,1000)', s1='if l!=[]: pass', s2='if l: pass', s3='if len(l): pass')

would print

s2 => 0.046 s1 => 0.086 s3 => 0.121