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

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

为此,我尝试了 %%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 现在都可以正常工作了。

最佳答案

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

Do not forget that单元格魔法以 %% 开头,线条魔法以 % 开头。

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

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

https://stackoverflow.com/questions/32565829/

相关文章:

mysql - 通过 shell 脚本使用 echo 命令自动化 mysql_secure_inst

python - 使用 python 和 BeautifulSoup 从网页中检索链接

linux - 在 Linux 中将多个 JPG 合并为单个 PDF

python - 如何跳过循环中的迭代?

python - 使用 Pandas 计算每个组的唯一值

c - Linux共享内存: shmget() vs mmap()?

c - Linux 中的 getch() 和 getche() 等价于什么?

linux - 在 shell 脚本中缩进多行输出

android - 如何在 Ubuntu 上安装 Android SDK?

python - 在 Python 中查找数字的所有因数的最有效方法是什么?