timeit模組可以用來測試一小段python**的執行速度。
timer是測量小段**執行速度的類。
class timeit.timer(stmt='pass
', setup='
pass
', timer=)
stmt引數是要測試的**語句(statment);
setup引數是執行**時需要的設定;
timer引數是乙個定時器函式,與平台有關。
timer物件.timeit(number=1000000)timer類中測試語句執行速度的物件方法。number引數是測試**時的測試次數,預設為1000000次。方法返回執行**的平均耗時,乙個float型別的秒數。
#-*- coding:utf-8 -*-
import
timeit
deft2():
li =
for i in range(10000):
li.insert(0, i)
deft0():
li =
for i in range(10000):
li.extend([i])
deft1():
li =
for i in range(10000):
deft3():
li =
for i in range(10000):
li +=[i]
deft3_1():
li =
for i in range(10000):
li = li +[i]
deft4():
li = [ i for i in range(10000)]
deft5():
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("
", 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
")
執行結果:pop操作測試insert 18.678989517seconds
extend 1.022223395000001seconds
+= 0.773258104seconds
+加法 126.929554195seconds
[i for i in range()] 0.36483252799999377seconds
list 0.19607099800001038 seconds
x = range(2000000)測試pop操作:從結果可以看出,"pop最後乙個元素"的效率遠遠高於"pop第乙個元素"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')
Python內建型別效能分析
python內建型別效能分析 timeit模組 timeit模組可以用來測試一小段python 的執行速度。class timeit.timer stmt pass setup pass timer timer是測量小段 執行速度的類。stmt引數是要測試的 語句 statment setup引數是...
Python內建型別效能分析
學習目標 掌握timeit模組的使用 timeit模組 timeit模組可以用來測試一小段python 的執行速度。class timeit.timer stmt pass setup pass timer timer是測量小段 執行速度的類。stmt引數是要測試的 語句 statment setu...
Python內建型別效能分析
使用到的知識點 timeit模組 timeit模組可以用來測試一小段python 的執行速度。class timeit.timer stmt pass setup pass timer timer是測量小段 執行速度的類。stmt引數是要測試的 語句 statment setup引數是執行 時需要的...