在 Python 中获取计时器滴答声 [英] Get timer ticks in Python
问题描述
我只是想为一段代码计时.伪代码如下:
start = get_ticks()do_long_code()打印花了"+(get_ticks()-开始)+秒."
这在 Python 中看起来如何?
更具体地说,我如何获得自午夜以来的滴答数(或者 Python 组织该时间的方式)?
time
模块中,有两个计时函数:time
和clock代码>.
time
给你墙"时间,如果这是你关心的.
然而,python docs 说clock
应该用于基准测试.请注意,clock
在不同的系统中表现不同:
- 在 MS Windows 上,它使用 Win32 函数 QueryPerformanceCounter(),分辨率通常优于微秒".它没有特殊含义,只是一个数字(它从您在流程中第一次调用
clock
时开始计数).
- 在 *nix 上,
clock
报告 CPU 时间.现在,这是不同的,而且很可能是您想要的值,因为您的程序几乎不是唯一请求 CPU 时间的进程(即使您没有其他进程,内核偶尔也会使用 CPU 时间).因此,这个数字通常小于墙上时间(即 time.time() - t0),在对代码进行基准测试时更有意义:
除此之外,timeit 模块具有 Timer
类应该使用最适合可用功能的基准测试.
¹ 除非线程妨碍了……
² Python ≥3.3:有time.perf_counter()
和 time.process_time()
.perf_counter
正在被 timeit
模块使用.
I'm just trying to time a piece of code. The pseudocode looks like:
start = get_ticks()
do_long_code()
print "It took " + (get_ticks() - start) + " seconds."
How does this look in Python?
More specifically, how do I get the number of ticks since midnight (or however Python organizes that timing)?
In the time
module, there are two timing functions: time
and clock
. time
gives you "wall" time, if this is what you care about.
However, the python docs say that clock
should be used for benchmarking. Note that clock
behaves different in separate systems:
- on MS Windows, it uses the Win32 function QueryPerformanceCounter(), with "resolution typically better than a microsecond". It has no special meaning, it's just a number (it starts counting the first time you call
clock
in your process).
# ms windows t0= time.clock() do_something() t= time.clock() - t0 # t is wall seconds elapsed (floating point)
- on *nix,
clock
reports CPU time. Now, this is different, and most probably the value you want, since your program hardly ever is the only process requesting CPU time (even if you have no other processes, the kernel uses CPU time now and then). So, this number, which typically is smaller¹ than the wall time (i.e. time.time() - t0), is more meaningful when benchmarking code:
# linux t0= time.clock() do_something() t= time.clock() - t0 # t is CPU seconds elapsed (floating point)
Apart from all that, the timeit module has the Timer
class that is supposed to use what's best for benchmarking from the available functionality.
¹ unless threading gets in the way…
² Python ≥3.3: there are time.perf_counter()
and time.process_time()
. perf_counter
is being used by the timeit
module.
这篇关于在 Python 中获取计时器滴答声的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!