timeit 效能測試

2022-08-19 17:45:10 字數 2087 閱讀 7118

可以用來

測試一小段python**的執行速度

。計時器類:class timeit.timer(stmt='pass', setup='pass', timer=)

timer是測量小段**執行速度的

類stmt:是要測試的**語句(statment),也可以傳方法名

setup:執行語句時,需要的設定,例如為了執行time.time()要引入time包

timer:是乙個定時器函式,與平台有關,不需要處理

函式:timeit.timer.timeit(number=1000000)

timer類中測試語句執行速度的物件方法

number引數是測試**時的測試次數,預設為

1000000

次方法返回執行**的平均耗時,乙個float型別的秒數

# -*- coding:utf-8 -*-def test1():

l =for i in range(3000

):def test2():

l =for i in range(3000

): l.insert(

0, i)

def test3():

l = [i for i in range(3000

)]def test4():

l = list(range(3000

))def test5():

l =for i in range(3000

): l.extend([i])

def test6():

l =for i in range(3000

): l = l +[i]

def test7():

l =for i in range(3000

): l +=[i]

from

timeit import timer

print(

'開始測試')

t1 = timer("

test1()

", "

from __main__ import test1")

print(

"", t1.timeit(number=1000), "秒"

)t2 = timer("

test2()

", "

from __main__ import test2")

print(

"insert:\t\t

", t2.timeit(number=1000), "秒"

)t3 = timer("

test3()

", "

from __main__ import test3")

print(

"推倒:\t\t

", t3.timeit(number=1000), "秒"

)t4 = timer("

test4()

", "

from __main__ import test4")

print(

"list:\t\t

", t4.timeit(number=1000), "秒"

)t5 = timer("

test5()

", "

from __main__ import test5")

print(

"extend:\t\t

", t5.timeit(number=1000), "秒"

)t6 = timer("

test6()

", "

from __main__ import test6")

print(

"+:\t\t

", t6.timeit(number=1000), "秒"

)t7 = timer("

test7()

", "

from __main__ import test7")

print(

"+=:\t\t

", t7.timeit(number=1000), "秒"

)print(

'結束測試

')

Python內建型別效能分析timeit模組

timeit模組可以用來測試一小段python 的執行速度 class timeit.timer stmt pass setup pass timer timer是測量小段 執行速度的類。stmt引數是要測試的 語句 statment setup引數是執行 時需要的設定 timer引數是乙個定時器函...

Python內建效能分析模組timeit

timeit模組可以用來測試一小段python 的執行速度。class timeit.timer stmt pass setup pass timer timer是測量小段 執行速度的類。stmt引數是要測試的 語句 statement setup引數是執行 時需要的設定 timer引數是乙個定時器...

筆記 timeit使用

需要做benchmark,非web程式。用python自帶的timeit模組。usr bin python coding utf 8 import xmlrpclib,timeit t timeit.timer s.interprete 三里庵的貴人香 import xmlrpclib ns xml...