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

Here is a handy function to use the timeit module from a script, creating a nice overview of the runtimes of one or more code snippets.

All command line flags that the timeit module accepts can be used.

The output can easily be customized.

Python, 30 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
30
def timeit(*args):
    "Run the timeit.main function with args, catch and parse the output."
    import sys
    import re
    import timeit
    import cStringIO

    prev_stdout = sys.stdout
    sys.stdout = cStringIO.StringIO()

    timeit.main(args)

    out = sys.stdout.getvalue()
    sys.stdout = prev_stdout
    # Parse the output, and apply our own formatting
    match = re.search(r"(\d+\.\d*|\d+) usec", out)
    time = float(match.group(1))
    print "%8.2f us: %s" % (time, args[-1])

if __name__ == "__main__":
    timeit("object()")
    timeit("list()")
    timeit("[]")
    timeit("int()")
    timeit("-s", "rng = range(32)",
           "[i for i in rng]    # a list comp")
    timeit("-s", "class ClassicClass: pass",
           "ClassicClass()      # create a classic class instance")
    timeit("-s", "class NewStyleClass(object): pass",
           "NewStyleClass()     # create a new style class instance")

This is the output from the script: <pre> 0.34 us: object() 0.59 us: list() 0.18 us: [] 0.48 us: int() 8.00 us: [i for i in rng] # a list comp 0.64 us: ClassicClass() # create a classic class instance 0.39 us: NewStyleClass() # create a new style class instance </pre>