在Python中获取计时器滴答数
我只是想给一段代码计时。伪代码看起来是这样的:
start = get_ticks()
do_long_code()
print "It took " + (get_ticks() - start) + " seconds."
在Python中,这样写怎么样?
更具体一点,我该如何获取从午夜开始到现在的时间(或者Python是怎么处理这个时间的)?
6 个回答
5
这是我最近开始使用的一个解决方案:
class Timer:
def __enter__(self):
self.begin = now()
def __exit__(self, type, value, traceback):
print(format_delta(self.begin, now()))
你可以这样使用它(你需要至少安装Python 2.5):
with Timer():
do_long_code()
当你的代码运行结束时,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
如果你有自己喜欢的格式化方法,或者觉得有更简单的做法,请告诉我!
33
你需要的是来自 time
模块的 time()
函数:
import time
start = time.time()
do_long_code()
print "it took", time.time() - start, "seconds."
不过,你也可以使用 timeit 模块来获得更多的选择。
37
在 time
模块里,有两个计时函数:time
和 clock
。如果你关心的是“实际时间”,那么可以用 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 时间)。所以,这个数字通常比实际时间要小¹,使用它来测试代码的性能更有意义:
# 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
模块使用的。