我想得到的时间花在单元格执行除了原始的输出从单元格。

为此,我尝试了%%timeit -r1 -n1,但它没有公开在cell中定义的变量。

%%time适用于只包含1条语句的cell。

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

最好的方法是什么?

更新

我已经在nbeextension中使用执行时间相当长一段时间了。这是伟大的。

更新2021 - 03

到目前为止,这是正确的答案。从本质上讲,%%time和%%timeit现在都像预期的那样工作。


当前回答

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

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

其他回答

这只是旧版本的一个问题。

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

%%time表示运行某项操作所花费的时间。它更适合报告长时间运行的操作,而不是进行低级优化。

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

%%timeit使用python timeit模块。医生说,

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

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


目前排名最高的答案,以及其他一些过时的答案——应该删除,因为它们现在非常具有误导性——确实有有用的评论,表明这些答案是不正确的:

即使没有打印最后一个语句,%%time也可以工作 现在将测试单元格中的变量考虑到下一个单元格中

当使用print(res)时,有时单元格中的格式是不同的,但jupyter/ipython带有显示。请参阅下面使用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语句可以保留格式。

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

不要忘记单元格魔术以%%开始,行魔术以%开始。

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

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

当遇到麻烦时,什么意味着什么:

时间还是??时间

详情如下:

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.

你可能还想查看python的剖析魔法命令% prunit给出类似-的东西

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}

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