Using the timeit module in a function with arguments

Example from the documentation

def test(): """Stupid test function""" L = [] for i in range(100): L.append(i) if __name__ == '__main__': import timeit print(timeit.timeit("test()", setup="from __main__ import test")) 

but how to call a function with parameters, for example, such a function:

 def test(some_object): """Stupid test function""" L = [] for i in range(100): L.append(some_object) 
+4
source share
3 answers

err, if I ask your question correctly, are you just looking for this?

 anobj = 42 # where it can be whatever object def test(foo): pass # do something with foo if __name__ == '__main__': import timeit print(timeit.timeit("test(anobj)", setup="from __main__ import test, anobj")) 
+6
source

Here's one solution that worked for me in this exact situation, until your arguments are huge matrices or something like that.


Let's say that I want to test the function foo (a, b, c) with the values ​​that I initialized inside my main function. I can make the following call without changing my code,

 timeit.Timer('foo({},{},{})'.format(a,b,c), "from __main__ import foo") 

If your arguments are strings, you must retype the quotation marks around the values:

 timeit.Timer('foo("{}","{}","{}")'.format(a,b,c), "from __main__ import foo") 

As a final warning, you should consider that your arguments will pass through the str () format, which may lead to their loss of precision and integrity of various types. Please check your inputs if you use this method!

+2
source

Do you want to use:

 def main(): import timeit print(timeit.timeit("test(some_object)")) # don't need to use the 'setup' def test(my_object): lst = [] for i in range(100): lst.append(my_object) if __name__ == '__main__': main() 
0
source

Source: https://habr.com/ru/post/1484478/


All Articles