Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use python timeit when passing variables to functions?

I'm struggling with this using timeit and was wondering if anyone had any tips

Basically I have a function(that I pass a value to) that I want to test the speed of and created this:

if __name__=='__main__':     from timeit import Timer     t = Timer(superMegaIntenseFunction(10))     print t.timeit(number=1) 

but when I run it, I get weird errors like coming from the timeit module.:

ValueError: stmt is neither a string nor callable 

If I run the function on its own, it works fine. Its when I wrap it in the time it module, I get the errors(I have tried using double quotes and without..sameoutput).

any suggestions would be awesome!

Thanks!

like image 960
Lostsoul Avatar asked Sep 23 '11 02:09

Lostsoul


People also ask

How do you Timeit a function in Python?

The syntax to execute your function inside timeit() on the command line is as follows: python -m timeit [-n N] [-r N] [-s S] [-t] [-c] [-h] [code statement ...] Command line parameters: -n N: the number of times you want the code to execute.

What does the Timeit function return?

The timeit() method returns the amount of time it takes to execute the statement repeatedly. The output of show_results() converts that into the amount of time it takes per iteration, and then further reduces the value to the average amount of time it takes to store one item in the dictionary.

What is the Timeit module used for?

This module provides a simple way to time small bits of Python code. It has both a Command-Line Interface as well as a callable one. It avoids a number of common traps for measuring execution times.


1 Answers

Make it a callable:

if __name__=='__main__':     from timeit import Timer     t = Timer(lambda: superMegaIntenseFunction(10))     print(t.timeit(number=1)) 

Should work

like image 174
Pablo Avatar answered Sep 28 '22 09:09

Pablo