File: class/Extras/Other/PriorClasses/scotts-sep12/timeit-demo.txt

# basic api: stmt strings (total = timeit, bestof = repeat+min)

>>> import timeit
>>> timeit.Timer(stmt='[x ** 2 for x in range(1000)]').timeit(1000)
1.0507178983677399
>>>
>>> timeit.timeit(stmt='[x ** 2 for x in range(1000)]', number=1000)
1.1060776148346605
>>>
>>> timeit.repeat(stmt='[x ** 2 for x in range(1000)]', number=1000, repeat=3)
[1.0697826829591293, 1.0652821035871227, 1.0688555899991314]
>>>
>>> min(timeit.repeat(stmt='[x ** 2 for x in range(1000)]', number=1000, repeat=3))
1.1139908932787534



# callable

>>> def testcase():
...     x = [x ** 2 for x in range(1000)]
...
>>> timeit.Timer(stmt=testcase).timeit(number=1000)
1.16211078101108
>>>
>>> timeit.timeit(stmt=testcase, number=1000)
1.1985195835559068
>>>
>>> timeit.repeat(stmt=testcase, number=1000, repeat=3)
[1.154840651926662, 1.0396133088910346, 0.9837678093971078]
>>>
>>> min(timeit.repeat(stmt=testcase, number=1000, repeat=3))
1.0809894139374592



# command-line api: run as script

c:\Python32\Lib\idlelib>cd ..

c:\Python32\Lib>timeit.py -n 1000 "[x ** 2 for x in range(1000)]"
1000 loops, best of 3: 1.1 msec per loop

c:\Python32\Lib>timeit.py -n 1000 -r 5 "[x ** 2 for x in range(1000)]"
1000 loops, best of 5: 1.09 msec per loop



# command-line api: run as module via -m

c:\Python32\Lib>cd c:\PP4E

c:\PP4E>C:\Python32\python -m timeit -n 1000 -r 5 "[x ** 2 for x in range(1000)]"
1000 loops, best of 5: 970 usec per loop



# verify order(1 msec) finding

c:\PP4E>c:\python32\python
Python 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)] on win32
>>> import timeit
>>> timeit.Timer(stmt='[x ** 2 for x in range(1000)]').timeit(number=1)
0.0012408481947598915



[Home page] Books Code Blog Python Author Train Find ©M.Lutz