准确测量python函数所需的时间

hoj*_*oju 41 python time profiling timeit

我需要测量程序某些部分的时间(不是用于调试,而是作为输出中的一个特性).准确性很重要,因为总时间只有几分之一秒.

当我遇到timeit时,我打算使用时间模块,声称可以避免测量执行时间的一些常见陷阱.不幸的是,它有一个糟糕的接口,将一个字符串作为输入然后进行评估.

那么,我是否需要使用此模块准确地测量时间,或者时间是否足够?它指的是什么陷阱?

谢谢

Cor*_*ter 28

您可以构建一个时序上下文(请参阅PEP 343)来非常轻松地测量代码块.

from __future__ import with_statement
import time

class Timer(object):
    def __enter__(self):
        self.__start = time.time()

    def __exit__(self, type, value, traceback):
        # Error handling here
        self.__finish = time.time()

    def duration_in_seconds(self):
        return self.__finish - self.__start

timer = Timer()

with timer:
    # Whatever you want to measure goes here
    time.sleep(2)

print timer.duration_in_seconds()    
Run Code Online (Sandbox Code Playgroud)


Sea*_*ira 27

根据Python 文档,它与不同操作系统中时间函数的准确性有关:

默认计时器功能取决于平台.在Windows上,time.clock()具有微秒粒度,但time.time()的粒度是1/60秒; 在Unix上,time.clock()具有1/100的第二个粒度,time.time()更加精确.在任一平台上,默认计时器功能都会测量挂钟时间,而不是CPU时间.这意味着在同一台计算机上运行的其他进程可能会干扰时间...在Unix上,您可以使用time.clock()来测量CPU时间.

直接从timeit.py代码中提取:

if sys.platform == "win32":
    # On Windows, the best timer is time.clock()
    default_timer = time.clock
else:
    # On most other platforms the best timer is time.time()
    default_timer = time.time
Run Code Online (Sandbox Code Playgroud)

此外,它直接处理为您设置运行时代码.如果你使用时间,你必须自己做.这当然可以节省您的时间

Timeit的设置:

def inner(_it, _timer):
    #Your setup code
    %(setup)s
    _t0 = _timer()
    for _i in _it:
        #The code you want to time
        %(stmt)s
    _t1 = _timer()
    return _t1 - _t0
Run Code Online (Sandbox Code Playgroud)

编辑,仅限Python 3:

从Python 3.3开始,您可以使用time.perf_counter()(系统范围的时序)或time.process_time()(进程范围的时序),就像您以前使用的方式一样time.clock():

from time import process_time

t = process_time()
#do some stuff
elapsed_time = process_time() - t
Run Code Online (Sandbox Code Playgroud)

新功能process_time不包括睡眠期间经过的时间.

  • `timeit.default_timer`是Python 3.3+上的`time.perf_counter`,即你可以在所有版本上使用`default_timer`. (3认同)

qid*_*qid 8

timeit模块看起来像是为了进行算法的性能测试而设计的,而不是简单的应用程序监控.您最好的选择可能是使用时间模块,time.time()在您感兴趣的段的开头和结尾调用,然后减去这两个数字.请注意,您获得的数字可能比系统计时器的实际分辨率多得多.


Kar*_*arl 5

我也对 timeit 糟糕的界面感到恼火,所以我为此创建了一个库,看看它的易用性


from pythonbenchmark import compare, measure
import time

a,b,c,d,e = 10,10,10,10,10
something = [a,b,c,d,e]

def myFunction(something):
    time.sleep(0.4)

def myOptimizedFunction(something):
    time.sleep(0.2)

# comparing test
compare(myFunction, myOptimizedFunction, 10, input)
# without input
compare(myFunction, myOptimizedFunction, 100)
Run Code Online (Sandbox Code Playgroud)

https://github.com/Karlheinzniebuhr/pythonbenchmark