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 .
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
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 .