Multiple ways to calculate elapsed time in Python example
This tutorial shows multiple ways to calculate the time taken for a function or elapsed time in Python.
elapsed time is the time taken for code execution i.e. mark the timer before the line or a function, next, mark the timer to stop and calculate the time difference between start and stop timer results in time taken.
How to calculate the time taken for Functions in Python
There are multiple ways we can get Elapsed time taken
Using the time module’s time function to get the elapsed time
import
time module- use the time() function before the line that you want to measure the time taken, hence it is the start time.
- Followed by code lines that contain a print message and sleep for 1 second
- Finally, the Call time() function stops the timer, It is stop time.
- Now, subtract stop with start time to know the elapsed time and a return floating number i.e seconds
import time
start = time.time()
print("Code execution1")
time. sleep(1)
print("Code execution2")
stop = time.time()
print(stop - start);
Output:
Code execution1
Code execution2
1.0005801000006613
Use timeit module timer function to calculate time taken in seconds
timeit
module provides default_timer function,
- start the timer before the code line,
timeit.default_timer
internally uses eithertime.time()
ortime.clock()
ortime.perfcounter()
based on OS type and python version. - time.sleep(1) waits for sleeper for 1 second
- next stop the timer using timer() function
- Subtract the stop and start timer, results in seconds
import time
from timeit import default_timer as timer
start = timer()
print("Code execution1")
time. sleep(1)
print("Code execution2")
stop = timer()
print(stop - start);
Output:
Code execution1
Code execution2
1.000243300004513
Use time module process_time function to calculate the time taken in seconds
time module has process_time function only in Python 3.x version. It returns the time taken, The time.sleep(1) time is not considered into the total elapsed time with this approach.
import time
start = time.process_time()
print("Code execution1")
time. sleep(1)
print("Code execution2")
stop = time.process_time()
print(stop - start);
datetime module now function to calculate time taken for a code
import
datetime
function fromdatetime
moduledatetime.now()
results start time with date and time- next, the code line contains code or function calls
- calls
datetime.now()
results stop time - subtract both times and return the difference of times in datetime format.
import time
from datetime import datetime
start = datetime.now()
print("Code execution1")
time. sleep(1)
print("Code execution2")
stop = datetime.now()
print(stop - start);
Output:
Code execution1
Code execution2
0:00:01.001805