干净的方法来测量Python中的多个代码执行时间

时间:2018-06-21 02:54:29

标签: python time

我想获取代码的几部分的执行时间。目前,我正在使用time.time(),但是在反复编写如下代码时,我会感到有些愚蠢:

start = time()
function1(args1)
print("Execution of function1: {}".format(time()-start))

start = time()
function2(args2)
print("Execution of function2: {}".format(time()-start))

start = time()
function3(args3)
print("Execution of function3: {}".format(time()-start))

请您知道更聪明的方法吗?我找不到任何可以执行以下操作的模块(例如):

chrono("Execution of function1")
function1(args1)

chrono("Execution of function2")
function2(args2)

chrono("Execution of function3")
function3(args3)

2 个答案:

答案 0 :(得分:0)

看看timeit模块。

https://docs.python.org/3/library/timeit.html

在该页面上,

>>> import timeit
>>> timeit.timeit('"-".join(str(n) for n in range(100))', number=10000)
0.3018611848820001
>>> timeit.timeit('"-".join([str(n) for n in range(100)])', number=10000)
0.2727368790656328
>>> timeit.timeit('"-".join(map(str, range(100)))', number=10000)
0.23702679807320237

答案 1 :(得分:0)

import time

def timeit(method):
    def timed(*args, **kw):
        ts = time.time()
        result = method(*args, **kw)
        te = time.time()
        print '%r (%r, %r) %2.2f sec' % \
            (method.__name__, args, kw, te-ts)
        return result
    return timed


@timeit
def function1():
    time.sleep(1)
    print 'function1'

>>> function1()
function1
'function1' ((), {}) 1.00 sec

使用此装饰器定义函数。

参考:

https://www.zopyx.com/andreas-jung/contents/a-python-decorator-for-measuring-the-execution-time-of-methods