timeit module: am I missing something obvious?
Peter Otten
__peter__ at web.de
Mon Feb 20 03:31:04 EST 2006
Steven D'Aprano wrote:
> When using the timeit module, you pass the code you
> want to time as strings:
>
> import timeit
> t = timeit.Timer("foo(x, y)", \
> """from module import foo
> x = 27
> y = 45
> """)
> elapsed_time = t.timeit()
>
> This is all very well, but it feels quite unnatural to
> me. Why am I passing strings around when functions are
> first class objects? Have I missed something obvious?
You are supposed to time small pieces of code where a function call would be
a significant overhead.
> I understand that sometimes you have to pass strings,
> because statements are NOT objects in Python. But what
> about when your code doesn't use statements?
>
> It seems to me it would be really useful to be able to
> do something like this:
>
> # this doesn't work...
> import timeit
> from module import foo
> x = 27
> y = 45
> t = timeit.Timer(foo, args=[x, y])
> elapsed_time = t.timeit()
>
> instead of messing about with setup strings and the like.
>
> Am I missing something obvious? Does this functionality
> already exist? Is there a reason why it can't exist?
Just do it :-)
I would suggest a slight modification:
t = timeit.Timer.for_function(foo, x, y, a=..., b=...)
And while you are at it you could also move the code that dynamically
adjusts the number of repetitions from the main() function into a Timer
method and make its invocation the default for the timeit() method. (If
that has not been done already, see
http://mail.python.org/pipermail/python-dev/2006-January/059952.html)
Peter
More information about the Python-list
mailing list