Python内置类型性能分析 - jerry

Welcome to Aiiyx !

Python内置类型性能分析

1、timeit模块

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

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

  1. Timer是测量小段代码执行速度的类。
  2. stmt参数是要测试的代码语句(statment);
  3. setup参数是运行代码时需要的设置;
  4. timer参数是一个定时器函数,与平台有关。

timeit.Timer.timeit(number=1000000)

Timer类中测试语句执行速度的对象方法。number参数是测试代码时的测试次数,默认为1000000次。方法返回执行代码的平均耗时,一个float类型的秒数。

2、list的操作测试

# 尽量不用+因为+是在不停的拷贝进第三个新的列表,而extends是扩展
def test1():  
   l = []
   for i in range(1000):
      l = l + [i]
def test2():
   l = []
   for i in range(1000):
      l.append(i)
def test3():
   l = [i for i in range(1000)]
def test4():
   l = list(range(1000))

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

from timeit import Timer

t1 = Timer("test1()", "from __main__ import test1")
print("concat ",t1.timeit(number=1000), "seconds")
t2 = Timer("test2()", "from __main__ import test2")
print("append ",t2.timeit(number=1000), "seconds")
t3 = Timer("test3()", "from __main__ import test3")
print("comprehension ",t3.timeit(number=1000), "seconds")
t4 = Timer("test4()", "from __main__ import test4")
print("list range ",t4.timeit(number=1000), "seconds")
timer5 = Timer("t5()", "from __main__ import t5")
print("extend:", timer5.timeit(1000))

# ('concat ', 1.7890608310699463, 'seconds')
# ('append ', 0.13796091079711914, 'seconds')
# ('comprehension ', 0.05671119689941406, 'seconds')
# ('list range ', 0.014147043228149414, 'seconds')
# (extend: 1.374474499999991)

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),即一个后插和前插入

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

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


timer6 = Timer("t6()", "from __main__ import t6")
print("append", timer6.timeit(1000))

timer7 = Timer("t7()", "from __main__ import t7")
print("insert(0)", timer7.timeit(1000))

# append 1.5830507
# insert(0) 22.985396299999998

3、list内置操作的时间复杂度

4、dict内置操作的时间复杂度

分享