I'm following a guide that suggests running %timeit following
where following
is a defined function.
I've tried using import timeit
but for some reason %timeit
does not run. I get a syntax error so clearly I'm not using it correctly. I've made a brief search that yielded pages on timeit
library but this confuses me even more in terms of usage.
I suspect that you are confusing %timeit
with timeit
:
%timeit
is an IPython "magic" command that will only work within an IPython shell session. Example useage would be:
In [1]: %timeit myfunc()
timeit
is a standard Python module - you can import timeit
in your script, and use timeit.timeit("expression")
etc. See the documentation for full details.
Here is an example showing one way you could use timeit.timeit
from within an IPython session:
In [2]: def foo(): pass
In [3]: import timeit
In [4]: timeit.timeit("foo()", setup="from __main__ import foo", number=10000)
Out[4]: 0.004509925842285156
In this case, our function foo
is defined within the global namespace of the IPython session, so we import it from __main__
. If it was defined in some external module then it would be necessary to modify the import
statement to reflect this, e.g.:
In [5]: timeit.timeit("pow(10, 3)", setup="from math import pow", number=10000)
Out[5]: 0.00642085075378418
Here I'm importing the pow
function from the math
module.
To try to reproduce %timeit
from IPython's magic with timeit
try this:
timeit.Timer(my_function).repeat(3, 1000)
%timeit takes the best of 3 count with n executions, where n is chosen internally (so 1000 in repeat() might not be a good choice)
reference:
-n N: execute the given statement N times in a loop. If this value is not given, a fitting value is chosen.
-r R: repeat the loop iteration R times and take the best result. Default: 3
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With