问题描述
我需要测量程序某些部分所花费的时间(不是用于调试,而是作为输出中的功能).准确性很重要,因为总时间将不到一秒钟.
I need to measure the time certain parts of my program take (not for debugging but as a feature in the output). Accuracy is important because the total time will be a fraction of a second.
当我遇到时间,它声称避免了一些用于测量执行时间的常见陷阱.不幸的是,它有一个糟糕的接口,需要一个字符串作为输入,然后才是eval的.
I was going to use the time module when I came across timeit, which claims to avoid a number of common traps for measuring execution times. Unfortunately it has an awful interface, taking a string as input which it then eval's.
那么,我需要使用此模块来准确地测量时间还是时间足够?它指的是什么陷阱?
So, do I need to use this module to measure time accurately, or will time suffice? And what are the pitfalls it refers to?
谢谢
推荐答案
根据Python 文档,它与不同操作系统中时间函数的准确性有关:
According to the Python documentation, it has to do with the accuracy of the time function in different operating systems:
直接从timeit.py
的代码中提取:
if sys.platform == "win32":
# On Windows, the best timer is time.clock()
default_timer = time.clock
else:
# On most other platforms the best timer is time.time()
default_timer = time.time
此外,它直接为您设置运行时代码.如果使用time
,则必须自己执行.当然,这为您节省了时间
In addition, it deals directly with setting up the runtime code for you. If you use time
you have to do it yourself. This, of course saves you time
Timeit的设置:
Timeit's setup:
def inner(_it, _timer):
#Your setup code
%(setup)s
_t0 = _timer()
for _i in _it:
#The code you want to time
%(stmt)s
_t1 = _timer()
return _t1 - _t0
Python 3:
从Python 3.3开始,您可以使用 time.perf_counter()
(系统范围内的时间)或 time.process_time()
(进程计时),就像您以前使用time.clock()
的方式一样:
Python 3:
Since Python 3.3 you can use time.perf_counter()
(system-wide timing) or time.process_time()
(process-wide timing), just the way you used to use time.clock()
:
from time import process_time
t = process_time()
#do some stuff
elapsed_time = process_time() - t
新功能process_time
将不包括睡眠时间.
The new function process_time
will not include time elapsed during sleep.
从Python 3.7开始,您还可以使用 process_time_ns()
类似于process_time()
,但返回时间以纳秒为单位.
Since Python 3.7 you can also use process_time_ns()
which is similar to process_time()
but returns time in nanoseconds.
这篇关于准确测量python函数所需的时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!