Tips on timeit.py
dmq at gain.com
Wed Mar 24 19:33:23 CET 2004
Module 'timeit.py' (LibRef 10.10) is a very convenient command-line
utility for timing code snippets, and avoids the pitfalls in using the
builtin module 'time' (LibRef 6.10). To time a typical function call
all it takes is:
% timeit.py -s "from PZfuncs import h23c ; freq = 2.0" "h23c(freq)"
100000 loops, best of 3: 6.29 usec per loop
My only complaint is that it is inconvenient to open a command window,
set the path to include the timeit module and any other modules I
might be using, cd to the working directory, then run the command.
Also, you have to use the primitive command-line editor if you want to
repeat the same test with other functions. It would be nice to do all
this from an already running Python session.
There are some examples in LibRef 10.10.2 on how to use timeit within
your current session, but they are not as easy as the command above,
and they don't do several runs, picking the best one. After a bit of
putzing around, I think I have the best way to use timeit without
leaving your current session. Here are some examples:
>>> import timeit
>>> tm = timeit.main
>>> tm(['-s', 'a = b = "a b"', 'a is b']) # <== One list, not a tuple of arguments.
10000000 loops, best of 3: 0.155 usec per loop
>>> tm(['-s', 'a = b = "a b"', 'a == b'])
10000000 loops, best of 3: 0.175 usec per loop
If you are doing something a little more complex, like the
command-line example above, then it is advantageous to first define a
>>> def timefunc(func):
args = ['-s', 'from PZfuncs import ' + func + '; freq = 2.0',
func + '(freq)']
100000 loops, best of 3: 4.92 usec per loop
100000 loops, best of 3: 5.85 usec per loop
Hope this will help someone.
More information about the Python-list