如何获取Python程序的执行时间?
我有一个 Python 命令行程序,需要一段时间才能完成。我想知道完成跑步所需的确切时间。
我查看了 timeit 模块,但它似乎仅适用于小代码片段。我想给整个节目计时。
I have a command line program in Python that takes a while to finish. I want to know the exact time it takes to finish running.
I've looked at the timeit
module, but it seems it's only for small snippets of code. I want to time the whole program.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(30)
Python 中最简单的方法:
这假设您的程序至少需要十分之一秒才能运行。
印刷:
The simplest way in Python:
This assumes that your program takes at least a tenth of second to run.
Prints:
在 Linux 或 Unix 中:
在 Windows 中,请参阅此 StackOverflow 问题:如何测量 Windows 命令行上命令的执行时间?< /a>
对于更详细的输出,
In Linux or Unix:
In Windows, see this StackOverflow question: How do I measure execution time of a command on the Windows command line?
For more verbose output,
我将此
timing.py
模块放入我自己的site-packages
目录中,然后在模块顶部插入import Timing
:我可以如果我想要显示的程序中有重要的阶段,还可以从我的程序中调用
timing.log
。但仅包含导入时间
就会打印开始时间和结束时间以及总体运行时间。 (请原谅我晦涩难懂的secondsToStr
函数,它只是将浮点数秒数格式化为 hh:mm:ss.sss 形式。)注意:可以找到上述代码的 Python 3 版本 此处或此处。
I put this
timing.py
module into my ownsite-packages
directory, and just insertimport timing
at the top of my module:I can also call
timing.log
from within my program if there are significant stages within the program I want to show. But just includingimport timing
will print the start and end times, and overall elapsed time. (Forgive my obscuresecondsToStr
function, it just formats a floating point number of seconds to hh:mm:ss.sss form.)Note: A Python 3 version of the above code can be found here or here.
我喜欢 datetime 模块提供的输出,其中时间增量对象以人类可读的方式根据需要显示天、小时、分钟等。
例如:
示例输出 例如
或
正如 JF Sebastian 提到的,这种方法可能会遇到一些本地时间的棘手情况,因此使用更安全:
I like the output the
datetime
module provides, where time delta objects show days, hours, minutes, etc. as necessary in a human-readable way.For example:
Sample output e.g.
or
As J.F. Sebastian mentioned, this approach might encounter some tricky cases with local time, so it's safer to use:
time.clock() 返回处理器时间,这使我们能够仅计算该进程使用的时间(无论如何在 Unix 上)。文档说“无论如何,这是用于对 Python 或计时算法进行基准测试的函数”
time.clock()
returns the processor time, which allows us to calculate only the time used by this process (on Unix anyway). The documentation says "in any case, this is the function to use for benchmarking Python or timing algorithms"我真的很喜欢 Paul McGuire 的答案,但我使用 Python 3。所以对于那些感兴趣的人:这里是他的答案的修改在 *nix 上与 Python 3 配合使用(我想,在 Windows 下,应该使用
clock()
而不是time()
):如果您发现这很有用,您仍然应该对他的答案而不是这个答案进行投票,因为他做了大部分工作;)。
I really like Paul McGuire's answer, but I use Python 3. So for those who are interested: here's a modification of his answer that works with Python 3 on *nix (I imagine, under Windows, that
clock()
should be used instead oftime()
):If you find this useful, you should still up-vote his answer instead of this one, as he did most of the work ;).
您可以使用 Python 分析器 cProfile 来测量 CPU 时间 以及每个函数内花费的时间以及每个函数被调用的次数。如果您想提高脚本的性能而不知道从哪里开始,这非常有用。 这个答案对另一个 StackOverflow 问题非常好。查看文档总是好的。
以下是如何从命令行使用 cProfile 分析脚本的示例:
You can use the Python profiler cProfile to measure CPU time and additionally how much time is spent inside each function and how many times each function is called. This is very useful if you want to improve performance of your script without knowing where to start. This answer to another Stack Overflow question is pretty good. It's always good to have a look in the documentation too.
Here's an example how to profile a script using cProfile from a command line:
只需使用
timeit
模块即可。它适用于 Python 2 和 Python 3。它会在几秒钟内返回,您可以了解执行时间。这很简单,但是您应该将它们编写在启动程序执行的主函数中。如果您想在出现错误时也获得执行时间,请使用参数“Start”并进行计算,如下所示:
Just use the
timeit
module. It works with both Python 2 and Python 3.It returns in seconds and you can have your execution time. It is simple, but you should write these in thew main function which starts program execution. If you want to get the execution time even when you get an error then take your parameter "Start" to it and calculate there like:
time.clock
已在 Python 3.3 中弃用,并将从 Python 3.8 中删除:使用time.perf_counter
或time.process_time
代替time.clock
has been deprecated in Python 3.3 and will be removed from Python 3.8: usetime.perf_counter
ortime.process_time
insteadtime.clock()
time.perf_counter()
time.process_time()
time.clock()
time.perf_counter()
time.process_time()
对于使用 Jupyter Notebook 的数据人员
,您可以在单元格中使用 Jupyter 的
%%time
魔法命令测量执行时间:输出
这只会捕获特定单元格的执行时间。如果您想捕获整个笔记本(即程序)的执行时间,您可以在同一目录中创建一个新笔记本,并在新笔记本中执行所有单元格:
假设上面的笔记本名为
example_notebook.ipynb
。在同一目录中的新笔记本中:输出
For the data folks using Jupyter Notebook
In a cell, you can use Jupyter's
%%time
magic command to measure the execution time:Output
This will only capture the execution time of a particular cell. If you'd like to capture the execution time of the whole notebook (i.e. program), you can create a new notebook in the same directory and in the new notebook execute all cells:
Suppose the notebook above is called
example_notebook.ipynb
. In a new notebook within the same directory:Output
以下代码片段以人类可读的
格式打印经过的时间。The following snippet prints elapsed time in a nice human readable
<HH:MM:SS>
format.与 @rogeriopvl 的响应类似,我添加了一个轻微的修改,以使用相同的库将长时间运行的作业转换为小时分钟秒。
样本输出
Similar to the response from @rogeriopvl I added a slight modification to convert to hour minute seconds using the same library for long running jobs.
Sample Output
对于函数,我建议使用我创建的这个简单的装饰器。
For functions, I suggest using this simple decorator I created.
我认为这是最好、最简单的方法:
或者使用装饰器:
I think this is the best and easiest way to do it:
Or with a decorator:
它运行
your_module.main()
函数一次,并使用time.time()
函数作为计时器打印经过的时间。要在 Python 中模拟
/usr/bin/time
,请参阅 带有 /usr/bin/time 的 Python 子进程:如何捕获计时信息但忽略所有其他输出?。要测量每个函数的 CPU 时间(例如,不包括
time.sleep()
期间的时间),您可以使用profile
模块 (cProfile 在 Python 2 上):
如果您想使用与
profile
模块相同的计时器,您可以将-p
传递给上面的timeit
命令。请参阅如何分析 Python 脚本?
It runs
your_module.main()
function one time and print the elapsed time usingtime.time()
function as a timer.To emulate
/usr/bin/time
in Python see Python subprocess with /usr/bin/time: how to capture timing info but ignore all other output?.To measure CPU time (e.g., don't include time during
time.sleep()
) for each function, you could useprofile
module (cProfile
on Python 2):You could pass
-p
totimeit
command above if you want to use the same timer asprofile
module uses.See How can you profile a Python script?
我在很多地方都遇到了同样的问题,所以我创建了一个便利包
horology
。您可以使用 pip install horology 来安装它,然后以优雅的方式进行安装:将输出:
或者更简单(如果您有一个函数):
将输出:
它负责单位和舍入。它适用于 python 3.6 或更高版本。
I was having the same problem in many places, so I created a convenience package
horology
. You can install it withpip install horology
and then do it in the elegant way:will output:
Or even simpler (if you have one function):
will output:
It takes care of units and rounding. It works with python 3.6 or newer.
我喜欢Paul McGuire的回答 也提出了一个更适合我的需求的上下文管理器形式。
I liked Paul McGuire's answer too and came up with a context manager form which suited my needs more.
在 IPython 中,“timeit”任何脚本:
In IPython, "timeit" any script:
使用 line_profiler。
line_profiler 将分析各行代码执行所需的时间。分析器通过 Cython 在 C 中实现,以减少分析的开销。
结果将是:
Use line_profiler.
line_profiler will profile the time individual lines of code take to execute. The profiler is implemented in C via Cython in order to reduce the overhead of profiling.
The results will be:
我使用了一个非常简单的函数来对部分代码执行进行计时:
要使用它,只需在代码之前调用它来测量以检索函数计时,然后在带注释的代码之后调用该函数即可。评论前面会显示时间。例如:
那么输出将如下所示:
I used a very simple function to time a part of code execution:
And to use it, just call it before the code to measure to retrieve function timing, and then call the function after the code with comments. The time will appear in front of the comments. For example:
Then the output will look like this:
我尝试使用以下脚本发现时差。
I tried and found time difference using the following scripts.
您只需使用 Python 即可完成此操作。没有必要让它变得复杂。
You do this simply in Python. There is no need to make it complicated.
Timeit是Python中的一个类,用于计算小代码块的执行时间。
Default_timer 是此类中的一个方法,用于测量挂钟计时,而不是 CPU 执行时间。因此其他进程的执行可能会干扰这一点。因此它对于小代码块很有用。
代码示例如下:
Timeit is a class in Python used to calculate the execution time of small blocks of code.
Default_timer is a method in this class which is used to measure the wall clock timing, not CPU execution time. Thus other process execution might interfere with this. Thus it is useful for small blocks of code.
A sample of the code is as follows:
首先,以管理员身份打开命令提示符(CMD)并在其中输入 -
pip install humanFriendly
代码:
输出:
First, install humanfriendly package by opening Command Prompt (CMD) as administrator and type there -
pip install humanfriendly
Code:
Output:
后来的答案,但我使用内置的
timeit
:code_to_test
内。number
参数指定代码应重复的次数。Later answer, but I use the built-in
timeit
:code_to_test
.number
argument specifies the amount of times the code should repeat.有一个 timeit 模块可用于计算 Python 代码的执行时间。
它在 Python 文档中提供了详细的文档和示例,26.6。 timeit — 测量小代码片段的执行时间。
There is a
timeit
module which can be used to time the execution times of Python code.It has detailed documentation and examples in Python documentation, 26.6. timeit — Measure execution time of small code snippets.
按照这个答案创建了一个简单但方便的工具。
用法:
输出:
Following this answer created a simple but convenient instrument.
Usage:
The output:
我使用 tictoc 的 tic 和 toc。
然后你可以在你的脚本中使用:
I use tic and toc from ttictoc.
Then you can use in your script: