程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python: measuring code runtime

編輯:Python

There are two main ways to measure the time required for code to run , Use time.time() , It's a universal approach , Or use timeit.timeit() Measuring small code snippets .

1 time()

This is a general method :

import time
def powers(limit):
return [x**2 for x in range(limit)]
start = time.time()
powers(5000000)
end = time.time()
print(end-start) # 1.0257349014282227 ( second )

Or put the relevant code for measuring time into a higher-order function measure_runtime in , Take the function as an argument , You can measure the time required for any function to run :

import time
def measure_runtime(func):
time_start = time.time()
func()
time_end = time.time()
print(time_end - time_start)
def powers(limit):
return [x**2 for x in range(limit)]
measure_runtime(lambda: powers(5000000)) # 1.006134033203125 second 

2 timeit()

This function is used to measure the time required for a small code segment to run :

This function has 5 Parameters :

timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000, globals=None)
timeit.timeit(stmt='', setup='', timer=time.perf_counter, number=1000000, globals=None)

stmt Is the code segment to be tested ,setup The function is similar to initializing variables in the code segment , stay stmt Before execution ,number If not set , that stmt Default execution 1000000 A million times , If stmt Execution once requires 1 second , A million seconds is a very long time , therefore number Parameters should generally be set .
usage :

import timeit
print(timeit.timeit("[x**2 for x in range(5000000)]", number=4))
print(timeit.timeit("list(map(lambda x: x**2, range(100)))", setup="", number=10000))
print(timeit.timeit(stmt='while x < 1000000: x += 1', setup='x = 0', number = 10000))

Running results :

4.101922899999408 # number = 4, Measured 4 Time , Sharing the 4 second 
0.23630119999870658
0.03228399999898102

timeit.timeit() Divide number, Will get stmt Perform the required... Once average time .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved