如何获得Python程序的执行时间?
我在Python中有一个命令行计划,需要一段时间才能完成。我想知道完成运行所需的确切时间。
我已经查看了 timeit
模块,但似乎仅适用于小型代码段。我想计时整个程序。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
我在Python中有一个命令行计划,需要一段时间才能完成。我想知道完成运行所需的确切时间。
我已经查看了 timeit
模块,但似乎仅适用于小型代码段。我想计时整个程序。
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
接受
或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
发布评论
评论(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
目录中,然后只插入导入timing
在我的模块的顶部:我可以如果我要显示的程序中有重大阶段,请在我的程序中调用
timing.log
。但是,仅包括导入时机
将打印开始和结束时间,以及整体过去的时间。 (请原谅我晦涩的sexionstostr
函数,它只是格式格式化的浮点数秒数为hh:mm:ss.sss form。)注意:可以找到上述代码的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
模块提供的位置,即Delta对象以人为可读的方式显示天数,小时,分钟等。例如:
样本输出
或
正如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 Profiler Cprofile来测量 cpu时间每个函数被调用多少次。如果您想在不知道从哪里开始的情况下提高脚本的性能,这将非常有用。 这个答案 to to to又有另一个堆栈;看一下文档也总是很好。
这是一个示例,如何使用命令行使用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一起使用。它在几秒钟内返回,您可以有执行时间。这很简单,但是您应该在启动程序执行的主函数中写下这些。如果您想获得执行时间,即使您获得错误,请使用参数“启动”并在此处计算以下计算:
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笔记本
href =“ https://ipython.readthedocs.io/en/stable/interactive/magics.html#magic time” rel =“ nofollow noreferrer”>
; code> %% %% 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
以下片段打印在一个不错的人类可读
&lt; hh:mm:ss&gt;
格式中。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()
函数作为计时器打印经过的时间。为了模拟
/usr/bin/time
在Python中,请参见 python subprocess with/usr/bin/time:捕获定时信息,但忽略所有其他输出?。要测量CPU时间(例如,请勿在
time.sleep()
)中为每个功能中包含时间,您可以使用配置文件
模块(cprofile
在Python 2上):您可以将
-p
转换为timeit
命令,如果要使用与profile>配置文件
模块使用的相同计时器。请参阅您如何配置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安装钟表
安装它,然后以优雅的方式进行:将输出:
甚至更简单(如果您有一个功能):
将输出:
它需要照顾单位和舍入。它可以与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.
我喜欢 >也提出了一个上下文管理器表格,该表格更适合我的需求。
I liked Paul McGuire's answer too and came up with a context manager form which suited my needs more.
在 ipython ,“ timeit” nimeit“任何脚本”:
In IPython, "timeit" any script:
使用 line_profiler 。
line_profiler将介绍执行时间单个代码的时间行。参考器在c中通过 cython ,以减少分析的开销。
结果将是:
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:
首先,安装 humanfriendly 通过打开命令提示符(cmd)作为管理员和在此处输入 -
pip安装人友好
代码:
输出:
First, install humanfriendly package by opening Command Prompt (CMD) as administrator and type there -
pip install humanfriendly
Code:
Output:
稍后答案,但我使用内置
timeit
a>:code_to_test
。号码
参数指定代码应重复的次数。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:
我使用ttictoc的TIC和TOC。
然后,您可以在脚本中使用:
I use tic and toc from ttictoc.
Then you can use in your script: