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 random
import time
# Record start time
start_time = time.time()
# Code to test for execution
sleep_for_secs = random.randint(1, 3)
print(f'Sleeping for {sleep_for_secs} seconds...')
time.sleep(sleep_for_secs)
# Record end time
end_time = time.time()
# Elapsed time
print('Elapsed Time:', end_time - start_time)
  • Lines 1–2: We import the time and random modules. 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_secs variable. Then we print a message that specifies how long the thread will sleep. Finally, we invoke the time.sleep method with sleep_for_secs as 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_time from end_time.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved