zoukankan      html  css  js  c++  java
  • python的list费时对比

    1. 生成列表的费时对比

    #_*_coding:utf-8_*_
    from timeit import Timer
    
    def test1():
        li =[]
        for i in range(10000):
            li.append(i)
    
    def test2():
        li = []
        for i in range(10000):
            li += [i]
    def test3():
        li = [i for i in range(10000)]
    
    def test4():
        li = list(range(10000))
    
    def test5():
        li = []
        for i in range(10000):
            li.extend([i])
    
    timer1 = Timer("test1()","from __main__ import test1")
    print("timer1_append(i):",timer1.timeit(number=1000),'seconds')
    
    timer2 = Timer("test2()","from __main__ import test2")
    print("timer2_[i for i in range(10000)]:",timer2.timeit(number=1000),'seconds')
    
    timer3 = Timer("test3()","from __main__ import test3")
    print("timer3_+=[i]:",timer3.timeit(number=1000),'seconds')
    
    timer4 = Timer("test4()","from __main__ import test4")
    print("timer4_list(range(10000)):",timer4.timeit(number=1000),'seconds')
    
    timer5 = Timer("test5()","from __main__ import test5")
    print("timer5_extend([i]):",timer5.timeit(number=1000),'seconds')
    
    输出:
    timer1_append(i): 0.753196745132229 seconds
    timer2_[i for i in range(10000)]: 0.6985947891373111 seconds
    timer3_+=[i]: 0.3255351125585728 seconds
    timer4_list(range(10000)): 0.188680616099971 seconds
    timer5_extend([i]): 1.0021387690009393 seconds
    
    

    2. 往列表中添加元素的费时对比

    #_*_coding:utf-8_*_
    from timeit import Timer
    
    def test1():
        li =[]
        for i in range(10000):
            li.append(i)
    
    def test7():
        li = []
        for i in range(10000):
            li.insert(0,i)
    
    
    timer1 = Timer("test1()","from __main__ import test1")
    print("timer1_append(i):",timer1.timeit(number=1000),'seconds')
    
    timer7 = Timer("test7()","from __main__ import test7")
    print("timer7_insert(0,i)):",timer7.timeit(number=1000),'seconds')
    
    输出:
    timer1_append(i): 0.7587850447087984 seconds
    timer7_insert(0,i)): 19.461151800961186 seconds
    

    写入自己的博客中才能记得长久
  • 相关阅读:
    预备作业02 : 体会做中学(Learning By Doing)
    7-1 货币转换
    秋季学校总结
    人生路上对我影响最大的三个老师
    自我介绍
    2019寒假作业3(抓老鼠啊~亏了还是赚了?)编程总结
    人生路上对我影响最大的三位老师
    自我介绍
    秋季学期学习总结
    7-1 抓老鼠啊~亏了还是赚了?
  • 原文地址:https://www.cnblogs.com/heris/p/14305601.html
Copyright © 2011-2022 走看看