Python内置类型性能分析

timeit模块

timeit模块可以用来测试一小段Python代码的执行速度。

Timer是测量小段代码执行速度的类。

class timeit.Timer(stmt=‘pass‘, setup=‘pass‘, timer=<timer function>)

stmt参数是要测试的代码语句(statment);
setup参数是运行代码时需要的设置;
timer参数是一个定时器函数,与平台有关。
Timer对象.timeit(number=1000000)
Timer类中测试语句执行速度的对象方法。number参数是测试代码时的测试次数,默认为1000000次。方法返回执行代码的平均耗时,一个float类型的秒数。

list的操作测试

# -*- coding:utf-8 -*-

import timeit

def t2():
    li = []
    for i in range(10000):
        li.insert(0, i)

def t0():
    li = []
    for i in range(10000):
        li.extend([i])

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

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

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

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

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


timer2 = timeit.Timer(stmt="t2()", setup="from __main__ import t2")
print("insert", timer2.timeit(number=1000), "seconds")

timer0 = timeit.Timer(stmt="t0()", setup="from __main__ import t0")
print("extend", timer0.timeit(number=1000), "seconds")

timer1 = timeit.Timer(stmt="t1()", setup="from __main__ import t1")
print("append", timer1.timeit(number=1000), "seconds")

timer3 = timeit.Timer(stmt="t3()", setup="from __main__ import t3")
print("+=", timer3.timeit(number=1000), "seconds")

timer3_1 = timeit.Timer(stmt="t3_1()", setup="from __main__ import t3_1")
print("+加法", timer3_1.timeit(number=1000), "seconds")

timer4 = timeit.Timer(stmt="t4()", setup="from __main__ import t4")
print("[i for i in range()]", timer4.timeit(number=1000), "seconds")

timer5 = timeit.Timer(stmt="t5()", setup="from __main__ import t5")
print("list", timer5.timeit(number=1000), "seconds")
执行结果:

insert 18.678989517 seconds
extend 1.022223395000001 seconds
append 0.6755100029999994 seconds
+= 0.773258104 seconds
+加法 126.929554195 seconds
[i for i in range()] 0.36483252799999377 seconds
list 0.19607099800001038 seconds

pop操作测试

x = range(2000000)
pop_zero = Timer("x.pop(0)","from __main__ import x")
print("pop_zero ",pop_zero.timeit(number=1000), "seconds")

x = range(2000000)
pop_end = Timer("x.pop()","from __main__ import x")
print("pop_end ",pop_end.timeit(number=1000), "seconds")

# (‘pop_zero ‘, 1.9101738929748535, ‘seconds‘)
# (‘pop_end ‘, 0.00023603439331054688, ‘seconds‘)

测试pop操作:从结果可以看出,"pop最后一个元素"的效率远远高于"pop第一个元素"

可以自行尝试下list的append(value)和insert(0,value),即一个后面插入和一个前面插入???

list内置操作的时间复杂度

Python内置类型性能分析

dict内置操作的时间复杂度

Python内置类型性能分析

相关推荐