This next sample will cover a very simple way we can utilize the timeit module to measure the time taken to execute two distinct functions:
import timeit
import time
def func1():
print("Function 1 Executing")
time.sleep(5)
print("Function 1 complete")
def func2():
print("Function 2 executing")
time.sleep(6)
print("Function 2 complete")
start_time = timeit.default_timer()
func1()
print(timeit.default_timer() - start_time)
start_time = timeit.default_timer()
func2()
print(timeit.default_timer() - start_time)
The preceding code takes a start, then executes each function, and then records an end time before printing the precise difference between the two times.
It should be noted that while we've managed to measure the time taken for each function, we've not actually utilized the timeit module to its full potential.
import timeit
import time
def func1():
print("Function 1 Executing")
time.sleep(3)
print("Function 1 complete")
def func2():
print("Function 2 executing")
time.sleep(2)
print("Function 2 complete")
t1 = timeit.Timer("func1()", setup="from __main__ import func1")
times = t1.repeat(repeat=2, number=1)
for t in times:
print("{} Seconds: ".format(t))
t2 = timeit.Timer("func2()", setup="from __main__ import func2")
times = t2.repeat(repeat=2, number=1)
for t in times:
print("{} Seconds: ".format(t))
In the last code, we instantiate two Timer objects, each taking in the function that they are going to be timing as well as the imports needed in order to run them within timeit.
We then call .repeat() on these two Timer objects, passing in repeat = 2 to determine how many times we want to time our code, and number = 1 to determine how many times we want to run these tests.
Executing the preceding code should provide the following output:
$ python3.6 timeitCode.py
Function 1 Executing
Function 1 complete
Function 1 Executing
Function 1 complete
3.002750840038061 Seconds:
3.0001289139618166 Seconds:
Function 2 executing
Function 2 complete
Function 2 executing
Function 2 complete
2.0005433409824036 Seconds:
2.00145923596574 Seconds: