Measuring the execution time of a Jupyter Notebook code cell

It seems that in Spyder (core IPython3) one can easily program a code cell by running a command %%time

or %%timeit

at the top of a 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 result in the execution time of the cell defined by the pair #%%

. This is how it works in Spyder, but doesn't quite work in the Jupyter Notebook environment.

Jupyter code cells are not defined by delimiters #%%

, rather they are created by clicking a button in the menu bar. And as far as I've tried the command %%time

and %%timeit

both raise the compilation error. Jupyter doesn't seem to be able to recognize them, but this is weird because my Jupyter actually uses the same IPython core as Spyder. One thing that works in Jupyter is commands %time

and %timeit

, but they can only measure the execution time of one line of code, i.e. Should be formulated as

%time blah blah

      

and it turns out that I can't even measure a loop for

that is more than one line long. Therefore, I don't need this method. Is there a way to estimate the execution time of a cell using a magic command %time(it)

and the like in Jupyter?

(PS: If in Spyder I attach a command %time

at the top of the cell, it gives Wall time: 0 ns

, because nothing happens on the same line and it does nothing.)

+4


source to share


2 answers


It depends on how you want to use the time information ...

If you just want to know how long it took a cell to execute for your own knowledge, the ExecuteTime Notebook Extension ( https://github.com/ipython-contrib/jupyter_contrib_nbextensions/tree/7672d429957aaefe9f2e71b15e3b78ebb9ba96d1/srcribsions/jupyter is a good solution) because it automatically provides time information for all code cells, which means less code maintenance as you don't have to add sync code all over the place. It also records the last completed date stamp, which is useful if you are using your laptop as a scientific journal.

However, if you want to use the time information programmatically, you will need to add code to write the time information to a variable. According to this answer ( Get the execution time of a block of code in Python 2.7 ), you can use the timeit module:



import timeit
start_time = timeit.default_timer()
# code you want to evaluate
elapsed = timeit.default_timer() - start_time

      

Obviously this is not as neat as using cell magic, but should get the job done.

As for how / if you can achieve the latter using cellular magic, I don't know.

+8


source


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



+1


source







All Articles