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

python的list费时对比python的list费时对比

上一篇:计算时间复杂度


下一篇:python for并行方法