Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is %timeit applied to a function or reference via parameters in command line?

Tags:

python

timeit

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.

like image 762
KhushV Avatar asked Sep 06 '25 12:09

KhushV


2 Answers

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()
    
  • timeitis 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.

like image 148
ali_m Avatar answered Sep 08 '25 22:09

ali_m


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

like image 31
t-bltg Avatar answered Sep 08 '25 22:09

t-bltg