1. 程式人生 > >Python程式碼時間測試

Python程式碼時間測試

常用套版

def f():
    pass

def main():
    from time import time
    t = time()
    f()
    print('時間消耗:%.2f秒' % (time() - t))

if __name__ == '__main__':
    main()

普通裝飾器

def fn_timer(fn):
    def function_timer(*args, **kwargs):
        """裝飾器"""
        from time import time
        t = time()
        result =
fn(*args, **kwargs) print('【%s】執行時間:%.2f秒' % (fn.__name__, time() - t)) return result return function_timer @fn_timer def f(): pass help(f)

wraps裝飾器

from time import time
from functools import wraps

def fn_timer(fn):
    @wraps(fn)
    def function_timer(*args, **kwargs)
: t = time() result = fn(*args, **kwargs) print('【%s】執行時間:%.2f秒' % (fn.__name__, time() - t)) return result return function_timer @fn_timer def f(): """用wraps後可以獲取help""" pass print(f.__doc__)

封裝在類中(強烈推薦)

from time import time
class A:
    def __init__(
self): self.t = time() def __del__(self): print(time() - self.t)

迴圈n次版

def f1():
    pass

def f2():
    pass

def test(func, n=999999):
    from time import time
    t = time()
    for i in range(n):
        func()
    print(time() - t)

if __name__ == '__main__':
    test(f1)
    test(f2)