Simple way to measure cell execution time in ipython notebook
I would like to get the time spent on the cell execution in addition to the original output from cell.
To this end, I tried %%timeit -r1 -n1
but it doesn't expose the variable defined within cell.
%%time
works for cell which only contains 1 statement.
In[1]: %%time
1
CPU times: user 4 µs, sys: 0 ns, total: 4 µs
Wall time: 5.96 µs
Out[1]: 1
In[2]: %%time
# Notice there is no out result in this case.
x = 1
x
CPU times: user 3 µs, sys: 0 ns, total: 3 µs
Wall time: 5.96 µs
What's the best way to do it?
Update
I have been using Execute Time in Nbextension for quite some time now. It is great.
Update 2021-03
As of now, this is the correct answer. Essentially, %%time
and %%timeit
both now work as one would expect.
The only way I found to overcome this problem is by executing the last statement with print.
Do not forget that cell magic starts with %%
and line magic starts with %
.
%%time
clf = tree.DecisionTreeRegressor().fit(X_train, y_train)
res = clf.predict(X_test)
print(res)
Notice that any changes performed inside the cell are not taken into consideration in the next cells, something that is counter intuitive when there is a pipeline:
An easier way is to use ExecuteTime plugin in jupyter_contrib_nbextensions package.
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime
%time
and %timeit
now come part of ipython's built-in magic commands
Use cell magic and this project on github by Phillip Cloud:
Load it by putting this at the top of your notebook or put it in your config file if you always want to load it by default:
%install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py
%load_ext autotime
If loaded, every output of subsequent cell execution will include the time in min and sec it took to execute it.
import time
start = time.time()
"the code you want to test stays here"
end = time.time()
print(end - start)