Una forma sencilla de medir el tiempo de ejecución de la celda en ipython notebook
Me gustaría obtener el tiempo dedicado a la ejecución de la celda además de la salida original de la celda.
Con este fin, intenté %%timeit -r1 -n1
pero no expone la variable definida dentro de la celda.
%%time
funciona para la celda que solo contiene 1 instrucción.
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
¿Cuál es la mejor manera de hacerlo?
Actualizar
He estado usando Tiempo de ejecución en Nbextension desde hace bastante tiempo. Es genial.
8 answers
Usa cell magic y este proyecto en github de Phillip Cloud:
Cárguelo colocando esto en la parte superior de su notebook o póngalo en su archivo de configuración si siempre desea cargarlo de forma predeterminada:
%install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py
%load_ext autotime
Si se carga, cada salida de la ejecución subsecuente de la celda incluirá el tiempo en min y sec que tomó ejecutarla.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-04-18 09:27:25
La única manera que encontré para superar este problema es ejecutando la última instrucción con print.
No olvide que la magia celular comienza con %%
y la magia de línea comienza con %
.
%%time
clf = tree.DecisionTreeRegressor().fit(X_train, y_train)
res = clf.predict(X_test)
print(res)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-02-22 19:16:51
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-03-07 08:19:17
Simplemente agregué %%time
al principio de la celda y obtuve el tiempo. Puede usar lo mismo en el clúster/ entorno virtual de Jupyter Spark usando lo mismo. Simplemente agregue %%time
en la parte superior de la celda y obtendrá la salida. En spark cluster usando Jupyter, agregué a la parte superior de la celda y obtuve una salida como la siguiente: -
[1] %%time
import pandas as pd
from pyspark.ml import Pipeline
from pyspark.ml.classification import LogisticRegression
import numpy as np
.... code ....
Output :-
CPU times: user 59.8 s, sys: 4.97 s, total: 1min 4s
Wall time: 1min 18s
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-11-16 16:18:47
Una forma más fácil es usar el complemento ExecuteTime en el paquete jupyter_contrib_nbextensions.
pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-05-17 06:10:23
Esto no es exactamente hermoso, pero sin software adicional
class timeit():
from datetime import datetime
def __enter__(self):
self.tic = self.datetime.now()
def __exit__(self, *args, **kwargs):
print('runtime: {}'.format(self.datetime.now() - self.tic))
Entonces puedes ejecutarlo como:
with timeit():
# your code, e.g.,
print(sum(range(int(1e7))))
% 49999995000000
% runtime: 0:00:00.338492
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-02-27 17:18:55
A veces el formato es diferente en una celda cuando se usa print(res)
, pero jupyter/ipython viene con un display
. Vea un ejemplo de la diferencia de formato usando pandas a continuación.
%%time
import pandas as pd
from IPython.display import display
df = pd.DataFrame({"col0":{"a":0,"b":0}
,"col1":{"a":1,"b":1}
,"col2":{"a":2,"b":2}
})
#compare the following
print(df)
display(df)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-06-15 22:46:30
Es posible que también desee ver el comando mágico de perfiles de python %prun
que da algo como -
def sum_of_lists(N):
total = 0
for i in range(5):
L = [j ^ (j >> i) for j in range(N)]
total += sum(L)
return total
Entonces
%prun sum_of_lists(1000000)
Volverá
14 function calls in 0.714 seconds
Ordered by: internal time
ncalls tottime percall cumtime percall filename:lineno(function)
5 0.599 0.120 0.599 0.120 <ipython-input-19>:4(<listcomp>)
5 0.064 0.013 0.064 0.013 {built-in method sum}
1 0.036 0.036 0.699 0.699 <ipython-input-19>:1(sum_of_lists)
1 0.014 0.014 0.714 0.714 <string>:1(<module>)
1 0.000 0.000 0.714 0.714 {built-in method exec}
Me resulta útil cuando se trabaja con grandes trozos de código.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-10 11:26:24