How to pass in argument to timeit.Timer

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Apr 28 16:37:25 EDT 2007


En Sat, 28 Apr 2007 15:48:11 -0300, silverburgh.meryl at gmail.com  
<silverburgh.meryl at gmail.com> escribió:

> I have a function in my python like this:
> def callFunc(line, no):
>       # some code
>
> And I want to do a performance test like this:
>  for line in f:
>         for i in range(int(count)):
>             t1 = timeit.Timer("callFunc(line, i)","from __main__
> import callFunc")
>             r1 = t1.timeit();
>             print r1;
>
> but when I run it, it can't recognize the parameter 'line' and 'i',
> can you please tell me how to fix it? i get this error:

They go in the "setup" parameter, like this:

     t1 = timeit.Timer("callFunc(line, i)","from __main__ import callFunc;  
line=%r; i=%d" % (line, i))

If it gets much longer, try this:

setup = """
 from __main__ import callFunc
line = %r
i = %d""" % (line, i)
stmt = "callFunc(line, i)"
t1 = timeit.Timer(stmt, setup)

-- 
Gabriel Genellina

PS: Please leave out the final ; - this is Python, not C nor ...
PS2: Perhaps the only place where I've used ; is with timeit. And even  
then you can avoid them as in the last example.



More information about the Python-list mailing list