1
function_to_test(test, mylist): #test as an int, mylist as a list of int
     do_something    
     return something

function_generates_a_list(min, max): #min, max are int
     do_something
     return a_List

I need to timeit the function_to_test and only this one. The purpose is to test code in order to determine which one is the best to test if a int is in a list of int. (test is a googolplex and mylist is a huge list starting from min to max). Yes, I already know the result of the function, I need to know how many times it will cost.

My problem is: which syntax have I to use with timeit if I want to pass a global list as a local parameter of a function I test?

7
  • Please don't use list as a variable name. Commented Jun 20, 2012 at 14:03
  • function_generates_a_list() has not to be tested. It simply generates the list wich is necessary to function_to_test wich has been to be timed. Commented Jun 20, 2012 at 14:04
  • I bet that you don't have an int that contains a googolplex. That would require, uh, quite a bit of storage. Commented Jun 20, 2012 at 14:04
  • @TimPietzcker : understand that i used "int" to speak for an integer, not for the built-in type of a language ... 3/2 is not a integer :) Commented Jun 20, 2012 at 14:07
  • OK, then tell me how you're storing the googolplex, you've made me curious. (What does 3/2 have to do with all this?) Commented Jun 20, 2012 at 14:08

1 Answer 1

1

The easiest way to do this is to create a function that takes no arguments, and calls your function with whatever arguments it needs:

mylist = function_generates_a_list()
def newfunc():
   function_to_test(mylist)

You can then call timeit(newfunc). You could also do this with a lambda expression - timeit(lambda: function_to_test(mylist)) is exactly equivalent to the above. If you're using timeit module-wise (ie, doing python -m timeit ...), you could also do this:

python -m timeit --setup='import mymodule' 'mymodule.newfunc()'

You could avoid having newfunc altogether by having a sufficiently convoluted setup string (the call to function_generates_a_list has to be in setup, possibly (as here) but not necessarily by happening when you import the module, if you don't want it to be part of your timings), but having the function makes things more flexible and less annoying.

Sign up to request clarification or add additional context in comments.

1 Comment

Uh, not sure i really woke up today :) THX COOP !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.