Python代码时间测试

常用套版

def word_count():
    pass


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


if __name__ == '__main__':
    main()

遍历列表时间测试

def f1(ls):
    for i in ls:
        print(i)
def f2(ls):
    for i in range(len(ls)):
        print(ls.pop())
if __name__ == '__main__':
    from time import time
    ls = list(range(99999))
    t0 = time()
    f1(ls)
    t1 = time()
    f2(ls)
    t2 = time()
    print(t1 - t0)
    print(t2 - t1)
测试结果
| function | time(秒) |
| - | - |
| f1 | 0.41 |
| f2 | 0.42 |

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】运行时间:%.4f秒' % (fn.__name__, time() - t))
        return result
    return function_timer


@fn_timer
def f():
    pass

猜你喜欢

转载自blog.csdn.net/Yellow_python/article/details/82710017