How to measure elapsed time in Python?
The elapsed time of a Python script is the execution duration of the program. We can find out this duration by calculating the difference between the execution start and end times of the script. For recording such timestamps, we use Python's time module's time() method.
Example
The code snippet below calculates and prints the execution time.
import randomimport time# Record start timestart_time = time.time()# Code to test for executionsleep_for_secs = random.randint(1, 3)print(f'Sleeping for {sleep_for_secs} seconds...')time.sleep(sleep_for_secs)# Record end timeend_time = time.time()# Elapsed timeprint('Elapsed Time:', end_time - start_time)
Lines 1–2: We import the
timeandrandommodules. We will use the former to generate timestamps and the latter to delay the execution by a random number of seconds.Lines 4–5: We record the timestamp before executing the main code.
Lines 7–10: We generate a random integer within the range 1 to 3 inclusive and store it inside the
sleep_for_secsvariable. Then we print a message that specifies how long the thread will sleep. Finally, we invoke thetime.sleepmethod withsleep_for_secsas the argument to suspend the thread for that many seconds.Lines 12–13: We record the timestamp after executing the main code.
Lines 15–16: We calculate the elapsed time and then print by subtracting
start_timefromend_time.
Free Resources