python性能测试值timeit的使用示例

from timeit import Timer


def t1():
    li = []
    for i in range(10000):
        li.append(i)


def t2():
    li = []
    for i in range(10000):
        li += [i]


def t3():
    li = [i for i in range(10000)]


def t4():
    li = list(range(10000))


if __name__ == '__main__':
    # 参数1运行语句,参数二导包。
    timer1 = Timer("t1()", "from __main__ import t1")
    print(timer1.timeit(1000))
    timer2 = Timer("t2()", "from __main__ import t2")
    print(timer2.timeit(1000))
    timer3 = Timer("t3()", "from __main__ import t3")
    print(timer3.timeit(1000))
    timer4 = Timer("t4()", "from __main__ import t4")
    print(timer4.timeit(1000))


posted @ 2019-06-05 14:06  公众号python学习开发  阅读(298)  评论(0编辑  收藏  举报