timeit in pycharm not resolving

Viewed 6201

I am doing something like this :

import numpy as np
import timeit

a = np.arange(1000)
%timeit a**2

Error :

TypeError: 'module' object is not callable

I want to print the time for the execution of statement a**2 in pycharm , can anyone please help me

Note : %timeit a**2 in working fine in Jupyter Notebook

3 Answers

%timeit and %%timeit are Jupyter magic commands, and only work inside IPython/Jupyter. They will not work in PyCharm or in Python scripts in general.

If you have PyCharm Professional, you can profile your script by clicking the profile button (to the right of the 'run', 'debug', and 'run with coverage' buttons).

If you don't you can time any Python 3 script by inserting

from datetime import datetime
start = datetime.now()

and

print(datetime.now() - start)

at the end.

Magic commands, like %timeit, are supported by pycharm, but only if executed in a python console, or a debugging console (as @Carlos de Lannoy noted). Just have a look at the pycharm documentation. Though they won't work if you put them in a script as you seem to do in your example.

Make sure you have ipython installed in the python environment used in your pycharm console, or it won't work. For example:

conda install -n myenv ipython

Example:

In[0]: import numpy as np
  ...: a = np.arange(1000)
  ...: %timeit a**2
2.36 µs ± 226 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

The %timeit magic doesn't work as noted by Andrey Portnoy, but you can still use the same function like this:

import numpy as np
import timeit
a = np.arange(1000)
t = timeit.timeit('a**2', globals=dict(a=a))
print(t)

You can also stop a script at a checkpoint in pycharm debugging mode and use the %timeit magic in the console. No idea why that does work though.

Related