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

Posted

技术标签:

【中文标题】在 ipython 笔记本中测量单元执行时间的简单方法【英文标题】:Simple way to measure cell execution time in ipython notebook 【发布时间】:2015-12-10 12:22:16 【问题描述】:

除了单元格的原始输出之外,我还想获取单元格执行所花费的时间。

为此,我尝试了%%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

最好的方法是什么?

更新

我使用Execute Time in Nbextension 已经有一段时间了。太棒了。

2021 年 3 月更新

截至目前,this 是正确答案。从本质上讲,%%time%%timeit 现在都可以正常工作了。

【问题讨论】:

你真的需要计时值的显示吗?为什么不把x 显示行放在下一个单元格中? 为什么不接受答案? 【参考方案1】:

%time%timeit 现在是 ipython 内置 magic commands 的一部分

【讨论】:

【参考方案2】:

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

如果你总是想默认加载它,可以把它放在你笔记本的顶部,或者把它放在你的配置文件中:

%install_ext https://raw.github.com/cpcloud/ipython-autotime/master/autotime.py
%load_ext autotime

如果已加载,后续单元执行的每个输出都将包括执行它所花费的时间(以分钟和秒为单位)。

【讨论】:

这不再有效,因为 %install_ext 已被弃用。有其他选择吗? 有一个Pull Request解决了这个问题(github.com/cpcloud/ipython-autotime/pull/5)然后你可以试试pip install ipython-autotime 现在 %%time 即使最后一条语句不是 print 也可以工作。 总结:1) pip install ipython-autotime 2) 在 jupyter 的第一个单元格中输入:%load_ext autotime【参考方案3】:

我发现解决这个问题的唯一方法是使用 print 执行最后一条语句。

Do not forget that cell magic 以 %% 开头,line magic 以 % 开头。

%%time
clf = tree.DecisionTreeRegressor().fit(X_train, y_train)
res = clf.predict(X_test)
print(res)

请注意,在单元格内执行的任何更改都不会在下一个单元格中考虑,这在存在管道时是反直觉的:

【讨论】:

现在 %%time 即使没有打印最后一条语句也可以工作,正如上面@rhaps0dy 指出的那样。 display(res) 也有效,并且是尝试显示 pandas 数据框或其他需要风格化输出的内容时的首选解决方案。 @dshefman 是的,这是正确的,并且也可以轻松移植到 databricks/spark 笔记本上。 当我们实现第一个单元%%timea=1但第二个单元不知道a是什么时,这不是问题吗? 仅供参考。我发现测试单元格中的变量现在被考虑到下一个单元格中。 (20/02/2020) - 费飞【参考方案4】:

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

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))

然后你可以像这样运行它:

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

% 49999995000000
% runtime: 0:00:00.338492

【讨论】:

【参考方案5】:

有时使用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)

display 语句可以保留格式。

【讨论】:

这是否执行单元格代码默认没有。次然后取平均值?那么作为“设置代码”的第一条语句呢?【参考方案6】:

我只是在单元格的开头添加了%%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

【讨论】:

这是否执行单元格代码默认没有。次然后取平均值?那么作为“设置代码”的第一条语句呢?【参考方案7】:

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

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
jupyter nbextension enable execute_time/ExecuteTime

【讨论】:

这是最被低估的答案! 致那些潜入答案海洋的人:这是一个,只需安装它,然后您就会以一种不错的格式看到每个单元格的执行时间 完美运行!还包括执行单元格时的时间戳 如果pip不起作用,github上会提到conda或直接安装选项github.com/ipython-contrib/jupyter_contrib_nbextensions【参考方案8】:

您可能还想查看 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

那么

%prun sum_of_lists(1000000)

将返回

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

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

【讨论】:

【参考方案9】:

您可以为此使用timeit 魔术函数。

%timeit CODE_LINE

或者在单元格上

%%timeit 

SOME_CELL_CODE

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

【讨论】:

【参考方案10】:
import time
start = time.time()
"the code you want to test stays here"
end = time.time()
print(end - start)

【讨论】:

完美。从 %%timeit 保存对象并在下一个单元格中使用太麻烦了【参考方案11】:

遇到麻烦意味着什么:

?%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.

【讨论】:

【参考方案12】:

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

%%time
<--code goes here-->

但这里要确保 %%time 是一个神奇的功能, 所以把它放在你代码的第一行

如果你把它放在你的代码之后,它会给你 使用错误,无法正常工作。

【讨论】:

【参考方案13】:

这只是旧版本的问题。

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

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

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

%%timeit 使用 python timeit 模块。该文档说,

它避免了 用于测量执行时间的常见陷阱的数量。另见蒂姆·彼得斯的 Python Cookbook 中“算法”章节的介绍,由 奥莱利。

希望该模块仍然相关,因为the reference it refers to 描述了诸如 (1) Windows 98 的解决方法仅更新 time.time() 每秒 18.2 次,以及 (2) 干扰所有将语句放在一行中,以避免增加行号计数器的字节码开销。


currently top-rated answer 以及其他一些过时的——应该删除,因为它们现在高度误导——确实有有用的 cmets 表明那些答案不正确:

%%time works even when the last statement is not print variables in the tested cell are now taken into consideration into the next cells

【讨论】:

【参考方案14】:

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

在 notebook 开头安装包

pip install ipython-autotime

然后通过在下面运行来加载扩展

%load_ext autotime

一旦你加载了它,任何在此之后运行的单元格都会给你单元格的执行时间。

如果你想关闭它,不用担心,只需通过在下面运行来卸载扩展程序

%unload_ext autotime

它非常简单,随时都可以使用。

如果您想了解更多,可以参考ipython-autime documentation或其github source

【讨论】:

以上是关于在 ipython 笔记本中测量单元执行时间的简单方法的主要内容,如果未能解决你的问题,请参考以下文章

代码中的ipython笔记本清除单元格输出

单元格的 ipython 笔记本背景颜色

如何在 Markdown 单元格 ipython/jupyter 笔记本中更改颜色?

如何将文本文件 (.py) 加载/编辑/运行/保存到 IPython 笔记本单元格中?

在笔记本中组合jupyter / ipython内核

IPython notebook:如何编写可以访问笔记本变量的单元魔术?