Easy Timeit Function in Python


Python provides a module timeit which allows quick timing of a piece of code. The straightforward example is given below.

import timeit

bar = timeit.Timer("a += 1", "a = 0")
print bar.timeit(number=10**6)
# call timeit a few times and returns a list of results
print bar.repeat(3, number=10**6)

The output is something like this.

0.0349752721557
[0.03478381873002872, 0.03506025879833556, 0.035819535067029715]
0.0357719051904
[0.03450737866172188, 0.035763499918048614, 0.03540067232839589]

The Timer constructor takes the first parameter as a statement to time, the second parameter an additional statement used for setup. The timeit() function measures the execution time of the first parameter and the repeat() function invokes many times of the timeit() and returns the measured results as a list.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
159 words
Last Post: Iterated Fibonacci Sequence in PHP
Next Post: HTML5 contenteditable Global Attribute

The Permanent URL is: Easy Timeit Function in Python

Leave a Reply