繁体   English   中英

想编写我在 Jupyter 笔记本中的空闲代码。 它正在使用 Timeit

[英]Would like to write code in idle that I have in Jupyter notebook. It is using Timeit

代码big_array= np.random.rand(1000000) %timeit sum(big_array)

上面的这段代码是在 jupyter notebook 中完成的,我如何在空闲时使用这段代码

有空闲

最直接的是将计时器构建到您的 Python 代码中,然后使用基于此处的 IDLE 运行它:

使用 IDLE 根据您提供的代码运行它:

import time
start = time.process_time()
import numpy as np
big_array= np.random.rand(1000000)
sum(big_array)  
print(time.process_time() - start)

如果你想使用 Pyinstrument(见下节),那也是可能的。 该文档建议您的代码为:

from pyinstrument import Profiler
profiler = Profiler()
profiler.start()
import numpy as np
big_array= np.random.rand(1000000)
sum(big_array)  
profiler.stop()
profiler.print()


使用 Python Profiler 工具 Pyinstrument 和您的代码作为脚本安装在您的系统上的替代方法

(我添加这个是因为这是更成熟的路线。当你开始开发更有能力的代码和功能时,你不会真的想要将时间/分析融入你的代码中。而且你可能不会在以后使用 IDLE .)

最简单的方法是让你的代码成为一个脚本,然后使用纯 Python 而不是 Jupyter/IPython 魔法来计时。 我根据您提供的代码收集,您将使用以下内容保存您的脚本my_script.py

import numpy as np
big_array= np.random.rand(1000000)
sum(big_array)

我尝试使用此处建议的cProfiler并没有太多运气来适应该代码示例,因此我使用了更现代的分析器pyinstrument ,我见过比我自己更了解 Python 的人提出的建议。 (后来看到这里我可以直接使用python -m cProfile my_script.py来使用 cProfiler,但是在先使用 pyinstrument 之后,我可以很快明白为什么推荐使用 pyinstrument。)

我使用pip install pyinstrument轻松安装了它。 然后在命令行/终端上运行以下命令:

pyinstrument my_script.py 

这相当于在命令行/终端上运行python my_script.py ,现在将其包装在 pyinstrument 分析中,请参阅文档

您会看到很多分析信息,包括时间:

jovyan@jupyter-binder-2dexamples-2drequirements-2dfg42zx6b:~$ pyinstrument my_script.py

  _     ._   __/__   _ _  _  _ _/_   Recorded: 15:05:41  Samples:  96
 /_//_/// /_\ / //_// / //_'/ //     Duration: 0.424     CPU time: 0.416
/   _/                      v4.1.1

Program: my_script.py

0.423 <module>  <string>:1
   [4 frames hidden]  <string>, runpy
      0.423 _run_code  runpy.py:64
      └─ 0.423 <module>  sum_test.py:1
         ├─ 0.224 <module>  numpy/__init__.py:1
         │     [231 frames hidden]  numpy, pickle, struct, <built-in>, pa...
         │        0.088 create_dynamic  <built-in>:0
         ├─ 0.176 sum  <built-in>:0
         │     [2 frames hidden]  <built-in>
         └─ 0.024 RandomState.rand  <built-in>:0
               [2 frames hidden]  <built-in>

To view this report with different options, run:
    pyinstrument --load-prev 2022-05-27T15-05-41 [options]

big_array= np.random.rand(1000000)中的数字添加更多的零,您可以真正看到sum()步骤成为运行该代码的整个过程中的限速步骤。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM