Search code examples
pythontimeipythonjupyter-notebookspyder

Measure runtime of a Jupyter Notebook code cell


It seems that in Spyder (IPython3 Kernel) one can easily time a code cell by running the %%time or %%timeit command at the top of the code cell:

#%%
%%time # or %%timeit which measures average runtime from multiple runs
....

#%% (the previous cell ends and the next begins)

Running the above code can get the runtime of the cell defined by the pair of #%%. This is how things work in Spyder, but doesn't quite work in the Jupyter Notebook environment.

In Jupyter code cells aren't defined by #%% delimiters, rather they are created by clicking a button in the menu bar. And as far as I tried, the command %%time and %%timeit both raise compilation error. It seems that Jupyter can't recognise them, but it's strange because my Jupyter actually uses the same IPython kernel as Spyder does. One thing that works in Jupyter is the %time and %timeit commands, but they can only measure the runtime of a one-line code, i.e., must be formulated like

%time blah blah

and it turns out I can't even measure a for loop which consists of more than one line. So this method is not desirable for me. Is there just any way to evaluate a cell runtime using the magic command %time(it) and the like in Jupyter?

(PS: If as in Spyder I attach a %time command at the top of a cell it will give Wall time: 0 ns because there is nothing following it in that same line and it actually measures nothing.)


Solution

  • Please put %%time at the very start of the cell even before any comments. This worked for me.