2 数据结构的性能分析 timeit

python数据结构的性能分析

https://www.cnblogs.com/bobo-zhang/p/10521769.html

from timeit import Timer #计算运行平均耗时

def lst():
    a_lst = []
    for i in range(1000):
        a_lst = a_lst+[i]

def lst1():
    a_lst = []
    for i in range(1000):
        a_lst.append(i)

def lst2():
    a_lst = [i for i in range(1000)]

def lst3():
    a_lst = list(range(1000))

if __name__ == '__main__':
    t1 = Timer('lst()','from __main__ import lst')  #stmt参数:表示即将进行测试的代码块语句。setup:运行代码块语句时所需要的设置
    print(t1.timeit(number=1000))  #number 1000000  million
    t2 = Timer('lst1()','from __main__ import lst1')
    print(t2.timeit(number=1000))
    t3 = Timer('lst2()','from __main__ import lst2')
    print(t3.timeit(number=1000))
    t4 = Timer('lst3()','from __main__ import lst3')
    print(t4.timeit(number=1000))
下面是输出结果
# 2.3458106781896984
# 0.12210792792831349
# 0.05140549197029687
# 0.024100440238528087

 

posted @ 2019-05-16 20:14  追风zz  阅读(139)  评论(0编辑  收藏  举报