Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass parameters of a function when using timeit.Timer()

Tags:

python

timer

This is the outline of a simple program

# some pre-defined constants A = 1 B = 2  # function that does something critical def foo(num1, num2):     # do something  # main program.... do something to A and B for i in range(20):     # do something to A and B     # and update A and B during each iteration  import timeit t = timeit.Timer(stmt="foo(num1,num2)")   print t.timeit(5) 

I just keep getting "global name foo is not defined"..... Can anyone help me on this? Thanks!

like image 495
CppLearner Avatar asked Feb 23 '11 02:02

CppLearner


People also ask

Can you use Timeit on a function in Python?

timeit() function returns the number of seconds it took to execute the code.

What value does Timeit return?

timeit() runs the setup statement one time, then calls the main statement count times. It returns a single floating point value representing the cumulative amount of time spent running the main statement.

Does Timeit return seconds or milliseconds?

The return value is seconds as a float. It is the total time taken to run the test (not counting the setup), so the average time per test is that number divided by the number argument, which defaults to 1 million.


1 Answers

The functions can use arguments in timeit if these are created using closures, we can add this behaviours by wrapping them in another function.

def foo(num1, num2):     def _foo():         # do something to num1 and num2         pass     return _foo  A = 1 B = 2  import timeit t = timeit.Timer(foo(A,B))   print(t.timeit(5)) 

or shorter, we can use functools.partial instead of explicit closures declaration

def foo(num1, num2):     # do something to num1 and num2     pass  A = 1 B = 2  import timeit, functools t = timeit.Timer(functools.partial(foo, A, B))  print(t.timeit(5)) 

EDIT using lambda, thanks @jupiterbjy

we can use lambda function without parameters instead of functools library

def foo(num1, num2):     # do something to num1 and num2     pass  A = 1 B = 2  import timeit t = timeit.Timer(lambda: foo(A, B))  print (t.timeit(5)) 
like image 195
Jose Ricardo Bustos M. Avatar answered Sep 18 '22 12:09

Jose Ricardo Bustos M.