简体   繁体   English

python中最精确的计时功能

[英]most precise timing function in python

I'm trying to build a program which has to do with very short time differences and I need a very accurate way to know how much time a statement took. 我正在尝试构建一个与时间差非常短的程序,我需要一种非常准确的方法来知道一条语句花费了多少时间。 When I use time.time(), even with hundreds of characters, it shows me that it took 0.0. 当我使用time.time()时,即使有数百个字符,也显示出它花了0.0。 (I measure the time.time() before and after and then subtract). (我测量time.time()之前和之后,然后减去)。 I checked to see if python compares string char by char or not with this code: 我检查了一下python是否用以下代码按字符比较char字符串:

time1 = time.time()
print s1 == s2
print (time.time() - time1)
time2 = time.time()
print s1 == s3
print time.time() - time2

(when s1,s2,s3 are very long strings, s2 is the same as s1 but the last char is different, and s3 is the same as s3 only that the first char is different) but the case I'm dealing with is a string that is about 10 characters, sometimes even less, and I need to find out how much time it takes to compare it to something else). (当s1,s2,s3是非常长的字符串时,s2与s1相同,但最后一个字符不同,而s3与s3相同,只是第一个字符不同))但是我要处理的情况是大约10个字符的字符串,有时甚至更少,我需要找出将它与其他字符进行比较需要花费多少时间。 Any help? 有什么帮助吗?

Edit: time.clock() worked great for me - it is much more accurate than time.time() (on Windows) 编辑:time.clock()对我来说很棒-它比time.time()准确得多(在Windows上)

You want time.perf_counter() : 您需要time.perf_counter()

a clock with the highest available resolution to measure a short duration 具有最高可用分辨率的时钟,可以测量较短的持续时间

timeit.default_timer() uses it on Python 3. On Python 2, it calls time.clock() on Windows and time.time() on other systems. timeit.default_timer()在Python 3上使用它。在Python 2上,它在Windows上调用time.clock() ,在其他系统上调用time.time()

Both time.clock() and time.perf_counter() use QueryPerformanceCounter() on Windows so you could use timeit.default_timer() on both Python 2 and 3 on Windows. 在Windows上, time.clock()time.perf_counter()使用QueryPerformanceCounter() ,因此在Windows 2和3上都可以使用timeit.default_timer()

time.perf_counter() (via pymonotonic(NULL) ) calls clock_gettime(CLOCK_HIGHRES) on Linux and mach_absolute_time() on OS X. You could call clock_gettime() using ctypes on Python 2 too (or find a backport that does it for you). time.perf_counter() (通过pymonotonic(NULL)在Linux上调用clock_gettime(CLOCK_HIGHRES) ,在OS X上调用 mach_absolute_time() 。您也可以在Python 2上使用ctypes调用clock_gettime() (或找到可以为您完成工作的mach_absolute_time() ) 。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM