在ipython笔记本中测量单元执行时间的简单方法

col*_*ang 148 python ipython ipython-notebook jupyter

除了来自单元格的原始输出之外,我还想花费在单元格执行上花费的时间.

为此,我试过%%timeit -r1 -n1但它没有公开在单元格中定义的变量.

%%time 适用于仅包含1个语句的单元格.

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
Run Code Online (Sandbox Code Playgroud)

最好的方法是什么?

更新

我已经在Nbextension中使用Execute Time已经有一段时间了.太棒了.

Sal*_*ali 377

我发现克服这个问题的唯一方法是使用print执行最后一个语句.

不要忘记,细胞魔法开始于%%,魔法线开始%.

%%time
clf = tree.DecisionTreeRegressor().fit(X_train, y_train)
res = clf.predict(X_test)
print(res)
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的答案,不知道为什么这是在没有选票的情况下坐下来 (31认同)
  • 供参考。我发现测试单元中的变量现在已被考虑到下一个单元中。(20/02/2020) - 费 (10认同)
  • 现在,即使没有打印最后一条语句,%% time也可以正常工作,如上文@ rhaps0dy所指出的。 (3认同)

rya*_*nmc 50

%time%timeit现在来IPython中的一部分内置的魔法命令


Phi*_*arz 36

在Phillip Cloud的github上使用cell magic和这个项目:

如果您希望在默认情况下加载它,请将其放在笔记本顶部或将其放入配置文件中来加载它:

%install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py
%load_ext autotime
Run Code Online (Sandbox Code Playgroud)

如果加载,后续单元格执行的每个输出将包括执行它所花费的时间(分钟和秒).

  • 有一个Pull Request解决这个问题(https://github.com/cpcloud/ipython-autotime/pull/5)然后你可以尝试`pip install ipython-autotime` (13认同)
  • 现在`%% time`即使最后一个语句不是'print`也能工作. (13认同)
  • 这不再有效,因为不推荐使用%install_ext.还有其他选择吗? (11认同)

min*_*ina 34

import time
start = time.time()
"the code you want to test stays here"
end = time.time()
print(end - start)
Run Code Online (Sandbox Code Playgroud)

  • 完美的。从 %%timeit 中保存对象并在下一个单元格中使用太麻烦了 (3认同)

小智 29

更简单的方法是在jupyter_contrib_nbextensions包中使用ExecuteTime插件.

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime
Run Code Online (Sandbox Code Playgroud)

  • 对于那些在答案之海中潜水的人:就是这个,只需安装它,然后您就会以良好的格式看到每个单元格的执行时间 (3认同)
  • 这是最被低估的答案! (2认同)

Mos*_*zar 21

您可以timeit为此使用魔术功能。

%timeit CODE_LINE
Run Code Online (Sandbox Code Playgroud)

或者在细胞上

%%timeit 

SOME_CELL_CODE
Run Code Online (Sandbox Code Playgroud)

https://nbviewer.jupyter.org/github/ipython/ipython/blob/1.x/examples/notebooks/Cell%20Magics.ipynb查看更多 IPython 魔法函数


Dha*_*dey 19

在 ipython Notebook 中测量单元执行时间的最简单方法是使用 ipython-autotime 包。

在笔记本的开头安装包

pip install ipython-autotime
Run Code Online (Sandbox Code Playgroud)

然后通过运行下面的命令来加载扩展

%load_ext autotime
Run Code Online (Sandbox Code Playgroud)

加载后,在此之后运行的任何单元格都会为您提供该单元格的执行时间。

如果您想关闭它,不用担心,只需通过运行以下命令卸载扩展即可

%unload_ext autotime
Run Code Online (Sandbox Code Playgroud)

它非常简单且易于使用,只要您需要即可使用。

如果你想了解更多,可以参考ipython-autime 文档或其github 源代码


nem*_*eel 12

如果你想在这里打印墙单元执行时间是一个技巧,请使用

%%time
<--code goes here-->
Run Code Online (Sandbox Code Playgroud)

但在这里请确保%%time是一个神奇的函数,所以把它放在代码的第一行

如果你把它放在你的代码的某些行之后,它会给你带来使用错误并且无法工作。


Har*_*_pb 11

我只是%%time在单元格的开头添加并获得了时间.您可以在Jupyter Spark集群/虚拟环境中使用相同的内容.只需%%time在单元格顶部添加即可获得输出.在使用Jupyter的spark集群上,我添加到单元格的顶部,我得到如下输出: -

[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
Run Code Online (Sandbox Code Playgroud)


and*_*otn 10

这只是旧版本的问题。

您现在需要做的就是放在%%time单元格的顶部。

在此处输入图片说明

%time衡量某件事运行所需的时间。报告长期运行的操作比进行低级优化更好。

%%timeit是一个基准测试工具,它一遍又一遍地运行语句以给出某些语句的平均运行时间以及标准偏差。由于语句重复执行的方式,%%timeit单元格中创建的变量在其他单元格中不可用。

在此处输入图片说明

%%timeit使用 pythontimeit模块。文档说,

它避免了许多用于测量执行时间的常见陷阱。另请参阅O'Reilly 出版的Python Cookbook 中Tim Peters 对“算法”一章的介绍。

希望该模块仍然相关,因为它所引用的参考描述了诸如(1)Windows 98time.time()每秒仅更新18.2 次的解决方法,以及(2)将所有语句塞到一行以避免字节码开销增加行号计数器。


目前收视率最高的答案,以及其他一些过时的,这应该是因为他们现在被删除的高度误导-有有益的意见,表明这些问题的答案是不正确的:


eaf*_*fit 7

这不是很漂亮,但没有额外的软件

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))
Run Code Online (Sandbox Code Playgroud)

然后你可以运行它:

with timeit():
    # your code, e.g., 
    print(sum(range(int(1e7))))

% 49999995000000
% runtime: 0:00:00.338492
Run Code Online (Sandbox Code Playgroud)


ble*_*man 7

有时使用时单元格中的格式不同print(res),但是jupyter/ipython附带了一个display.使用下面的pandas查看格式差异的示例.

%%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)
Run Code Online (Sandbox Code Playgroud)

display语句可以保留格式. 截图


mar*_*xor 5

你可能还想看看 python 的分析魔法命令%prun,它给出了类似的东西 -

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
Run Code Online (Sandbox Code Playgroud)

然后

%prun sum_of_lists(1000000)
Run Code Online (Sandbox Code Playgroud)

将返回

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}
Run Code Online (Sandbox Code Playgroud)

我发现它在处理大块代码时很有用。


pro*_*sti 5

当遇到困难时意味着什么:

?%timeit或者??timeit

要获取详细信息:

Usage, in line mode:
  %timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] statement
or in cell mode:
  %%timeit [-n<N> -r<R> [-t|-c] -q -p<P> -o] setup_code
  code
  code...

Time execution of a Python statement or expression using the timeit
module.  This function can be used both as a line and cell magic:

- In line mode you can time a single-line statement (though multiple
  ones can be chained with using semicolons).

- In cell mode, the statement in the first line is used as setup code
  (executed but not timed) and the body of the cell is timed.  The cell
  body has access to any variables created in the setup code.
Run Code Online (Sandbox Code Playgroud)