使用Time模块测量经过的时间

rec*_*gle 302 python time elapsed

使用python中的Time模块可以测量经过的时间吗?如果是这样,我该怎么做?

我需要这样做,以便如果光标已在窗口小部件中持续一段时间,则会发生事件.

Vad*_*der 475

start_time = time.time()
# your code
elapsed_time = time.time() - start_time
Run Code Online (Sandbox Code Playgroud)

您还可以编写简单的装饰器来简化各种功能的执行时间测量:

import time
from functools import wraps

PROF_DATA = {}

def profile(fn):
    @wraps(fn)
    def with_profiling(*args, **kwargs):
        start_time = time.time()

        ret = fn(*args, **kwargs)

        elapsed_time = time.time() - start_time

        if fn.__name__ not in PROF_DATA:
            PROF_DATA[fn.__name__] = [0, []]
        PROF_DATA[fn.__name__][0] += 1
        PROF_DATA[fn.__name__][1].append(elapsed_time)

        return ret

    return with_profiling

def print_prof_data():
    for fname, data in PROF_DATA.items():
        max_time = max(data[1])
        avg_time = sum(data[1]) / len(data[1])
        print "Function %s called %d times. " % (fname, data[0]),
        print 'Execution time max: %.3f, average: %.3f' % (max_time, avg_time)

def clear_prof_data():
    global PROF_DATA
    PROF_DATA = {}
Run Code Online (Sandbox Code Playgroud)

用法:

@profile
def your_function(...):
    ...
Run Code Online (Sandbox Code Playgroud)

您可以同时分析多个功能.然后打印测量值只需调用print_prof_data():

  • 值得添加/注意,经过时间的度量单位为秒. (33认同)
  • 您还可以查看[profilehooks](http://pypi.python.org/pypi/profilehooks)`pip install profilehooks`及其[主页](http://mg.pov.lt/profilehooks/ ) (11认同)
  • 请注意,从Python 3.3开始,在测量超时或持续时间时,应该使用`time.monotonic()`而不是`time.time()`.https://docs.python.org/3/library/time.html#time.monotonic (11认同)
  • @EricKramer谢谢!我的巨大宠物peev,解释测量而不定义测量单位.作为一个.NET家伙第一次将他的脚趾浸入Python中,我自动地想到了"毫秒". (4认同)
  • 如果(例如)更改系统时钟,则可能不起作用,并且可能没有亚秒分辨率。正确答案:https://stackoverflow.com/a/47637891/476716 (2认同)

lal*_*lli 91

time.time() 会做的.

import time

start = time.time()
# run your code
end = time.time()

elapsed = end - start
Run Code Online (Sandbox Code Playgroud)

你可能想看看这个问题,但我认为没有必要.

  • 是的,时间以秒为单位 (4认同)
  • `time.time()` 是一个坏主意,因为系统时钟可以重置,这会让你回到过去。`time.monotonic()` 负责处理这个问题(单调=它只向前推进)。`time.perf_counter()` 也是单调的,但具有更高的精度,因此建议将其用于挂钟时间。 (3认同)

Rut*_*ste 59

对于想要更好格式化的用户,

import time
start_time = time.time()
# your script
elapsed_time = time.time() - start_time
time.strftime("%H:%M:%S", time.gmtime(elapsed_time))
Run Code Online (Sandbox Code Playgroud)

将打印出来,持续2秒:

'00:00:02'
Run Code Online (Sandbox Code Playgroud)

一秒钟7分钟:

'00:07:01'
Run Code Online (Sandbox Code Playgroud)

请注意,gmtime的最小时间单位是秒.如果您需要微秒,请考虑以下事项:

import datetime
start = datetime.datetime.now()
# some code
end = datetime.datetime.now()
elapsed = end - start
print(elapsed)
# or
print(elapsed.seconds,":",elapsed.microseconds) 
Run Code Online (Sandbox Code Playgroud)

strftime 文档

  • 谢谢!现在我已经习惯了新的.'{:02d}:{:02d}:{:02d}'.format(e // 3600,(e%3600 // 60),e%60) (2认同)

Sto*_*ica 40

为了最佳度量经过时间(自Python 3.3起),请使用time.perf_counter().

返回性能计数器的值(以小数秒为单位),即具有最高可用分辨率的时钟,以测量短持续时间.它确实包括睡眠期间经过的时间,并且是系统范围的.返回值的参考点未定义,因此只有连续调用结果之间的差异才有效.

对于小时/天的量级测量,您不关心亚秒级分辨率,因此请使用time.monotonic().

返回单调时钟的值(以小数秒为单位),即不能倒退的时钟.时钟不受系统时钟更新的影响.返回值的参考点未定义,因此只有连续调用结果之间的差异才有效.

在许多实现中,这些实际上可能是相同的.

在3.3之前,你会被困住time.clock().

在Unix上,将当前处理器时间返回为以秒为单位的浮点数.精确度,实际上是"处理器时间"含义的定义,取决于同名C函数的精度.

在Windows上,此函数返回自第一次调用此函数以来经过的挂钟秒,作为浮点数,基于Win32函数QueryPerformanceCounter().分辨率通常优于1微秒.


Python 3.7的更新

Python 3.7中的新功能是PEP 564 - 添加具有纳秒分辨率的新时间函数.

使用这些可以进一步消除舍入和浮点错误,特别是如果您测量非常短的时间,或者您的应用程序(或Windows机器)长时间运行.

分辨率perf_counter()在大约100天后开始崩溃.因此,例如在一年的正常运行时间之后,它可以测量的最短间隔(大于0)将比它开始时更大.


Nur*_*hid 6

您需要导入时间,然后使用time.time()方法来了解当前时间.

import time

start_time=time.time() #taking current time as starting time

#here your code

elapsed_time=time.time()-start_time #again taking current time - starting time 
Run Code Online (Sandbox Code Playgroud)


Tor*_*ora 6

持续较长时间.

import time
start_time = time.time()
...
e = int(time.time() - start_time)
print('{:02d}:{:02d}:{:02d}'.format(e // 3600, (e % 3600 // 60), e % 60))
Run Code Online (Sandbox Code Playgroud)

会打印

00:03:15
Run Code Online (Sandbox Code Playgroud)

如果超过24小时

25:33:57
Run Code Online (Sandbox Code Playgroud)

这是受到Rutger Hofste的回答的启发.谢谢Rutger!


T.M*_*.M. 5

另一个计时的好方法是使用with python 结构。

with结构会自动调用__enter____exit__方法,这正是我们计时所需的。

让我们创建一个Timer类。

from time import time

class Timer():
    def __init__(self, message):
        self.message = message
    def __enter__(self):
        self.start = time()
        return None  # could return anything, to be used like this: with Timer("Message") as value:
    def __exit__(self, type, value, traceback):
        elapsed_time = (time() - self.start) * 1000
        print(self.message.format(elapsed_time))
Run Code Online (Sandbox Code Playgroud)

然后,可以像这样使用 Timer 类:

with Timer("Elapsed time to compute some prime numbers: {}ms"):
    primes = []
    for x in range(2, 500):
        if not any(x % p == 0 for p in primes):
            primes.append(x)
    print("Primes: {}".format(primes))
Run Code Online (Sandbox Code Playgroud)

结果如下:

素数:[2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89 , 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 22 7 , 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367, 3 73 、 379、 383、 389、 397、 401、 409、 419、 421、 431、 433、 439、 443、 449、 457、 461、 463、 467、 479、 487、 491、 499]

计算一些素数所用的时间:5.01704216003418ms


xjc*_*jcl 5

在编程中,有两种主要的时间测量方法,其结果不同:

>>> print(time.process_time()); time.sleep(10); print(time.process_time())
0.11751394000000001
0.11764988400000001  # took  0 seconds and a bit
>>> print(time.perf_counter()); time.sleep(10); print(time.perf_counter())
3972.465770326
3982.468109075       # took 10 seconds and a bit
Run Code Online (Sandbox Code Playgroud)
  • 处理器时间:这是此特定进程在 CPU 上主动执行所花费的时间。睡眠、等待 Web 请求或仅执行其他进程的时间不会对此产生影响。

    • time.process_time()
  • 挂钟时间:这是指“挂在墙上的时钟”已经过去了多少时间,即在实时之外。

    • time.perf_counter()

      • time.time() 还可以测量挂钟时间,但可以重置,因此您可以回到过去
      • time.monotonic() 无法重置(单调 = 只前进)但精度低于 time.perf_counter()