在Python中获取计时器滴答

and*_*wrk 41 python timer

我只想尝试一段代码.伪代码看起来像:

start = get_ticks()
do_long_code()
print "It took " + (get_ticks() - start) + " seconds."
Run Code Online (Sandbox Code Playgroud)

这看起来如何用Python?

更具体地说,我如何得到午夜以来的滴答数(或者Python组织那个时间)?

tzo*_*zot 34

time模块中,有两个定时功能:timeclock.time给你"墙"时间,如果这是你关心的.

但是,python 文档clock应该用于基准测试.请注意,clock在不同的系统中行为不同:

  • 在MS Windows上,它使用Win32函数QueryPerformanceCounter(),"分辨率通常优于微秒".它没有特殊含义,它只是一个数字(它会clock在您第一次调用过程中开始计算).
    # ms windows
    t0= time.clock()
    do_something()
    t= time.clock() - t0 # t is wall seconds elapsed (floating point)
  • 在*nix上,clock报告CPU时间.现在,这是不同的,并且很可能是您想要的值,因为您的程序几乎不是唯一请求CPU时间的进程(即使您没有其他进程,内核时不时地使用CPU时间).因此,这个数字通常小于壁时间(即time.time() - t0),在对代码进行基准测试时更有意义:
    # linux
    t0= time.clock()
    do_something()
    t= time.clock() - t0 # t is CPU seconds elapsed (floating point)

除此之外,timeit模块还有一个Timer类,它应该使用最好的功能来进行基准测试.

¹除非线程妨碍...

²Python≥3.3:有time.perf_counter()time.process_time().perf_counter正在被timeit模块使用.


bla*_*ing 31

你需要的是模块的time()功能time:

import time
start = time.time()
do_long_code()
print "it took", time.time() - start, "seconds."
Run Code Online (Sandbox Code Playgroud)

您可以使用timeit模块获得更多选项.


lee*_*ade 5

这是我最近开始使用的解决方案:

class Timer:
    def __enter__(self):
        self.begin = now()

    def __exit__(self, type, value, traceback):
        print(format_delta(self.begin, now()))
Run Code Online (Sandbox Code Playgroud)

你可以这样使用它(你至少需要 Python 2.5):

with Timer():
    do_long_code()
Run Code Online (Sandbox Code Playgroud)

当您的代码完成时,Timer 会自动打印出运行时间。甜的!如果我想在 Python 解释器中快速调整某些东西,这是最简单的方法。

这是“now”和“format_delta”的示例实现,尽管您可以随意使用您喜欢的时间和格式设置方法。

import datetime

def now():
    return datetime.datetime.now()

# Prints one of the following formats*:
# 1.58 days
# 2.98 hours
# 9.28 minutes # Not actually added yet, oops.
# 5.60 seconds
# 790 milliseconds
# *Except I prefer abbreviated formats, so I print d,h,m,s, or ms. 
def format_delta(start,end):

    # Time in microseconds
    one_day = 86400000000
    one_hour = 3600000000
    one_second = 1000000
    one_millisecond = 1000

    delta = end - start

    build_time_us = delta.microseconds + delta.seconds * one_second + delta.days * one_day

    days = 0
    while build_time_us > one_day:
        build_time_us -= one_day
        days += 1

    if days > 0:
        time_str = "%.2fd" % ( days + build_time_us / float(one_day) )
    else:
        hours = 0
        while build_time_us > one_hour:
            build_time_us -= one_hour
            hours += 1
        if hours > 0:
            time_str = "%.2fh" % ( hours + build_time_us / float(one_hour) )
        else:
            seconds = 0
            while build_time_us > one_second:
                build_time_us -= one_second
                seconds += 1
            if seconds > 0:
                time_str = "%.2fs" % ( seconds + build_time_us / float(one_second) )
            else:
                ms = 0
                while build_time_us > one_millisecond:
                    build_time_us -= one_millisecond
                    ms += 1
                time_str = "%.2fms" % ( ms + build_time_us / float(one_millisecond) )
    return time_str
Run Code Online (Sandbox Code Playgroud)

如果您有首选的格式化方法,或者是否有更简单的方法来完成所有这些,请告诉我!