Okay, the most common and reliable way to measure the execution time of a Python program is to record the time at the beginning and again at the end, and then calculate the difference. Using a try...finally block is a good practice to ensure the end time is recorded and printed even if an error occurs in your main code.
Here's the standard approach using the time module, specifically time.perf_counter() which is recommended for measuring durations:
python
import time
import sys # Optional: used here to demonstrate potential errors
# --- Record the start time as early as possible ---
start_time = time.perf_counter()
try:
# --- Your main program code goes here ---
print("Program started...")
# Simulate doing some work
time.sleep(2.5) # Sleep for 2.5 seconds
print("Doing more work...")
time.sleep(1.0) # Sleep for 1 second
# Simulate a successful finish
print("Program finished its main tasks.")
# --- Optional: Uncomment the line below to simulate an error ---
# print("This will cause an error: " + 123)
except Exception as e:
# --- Handle any errors gracefully if needed ---
print(f"An error occurred during execution: {e}", file=sys.stderr)
# Note: The 'finally' block will still run after this
finally:
# --- This block *always* executes, regardless of errors ---
# Record the end time
end_time = time.perf_counter()
# Calculate the duration
duration = end_time - start_time
# Print the time taken
print("-" * 30) # Separator for clarity
print(f"Program finished in {duration:.4f} seconds.")
print("-" * 30)
# --- Any code after the finally block will also execute if no unhandled error occurred ---
# (though in this pattern, the program is usually done after the finally block)
Explanation:
import time: Imports the necessary module to work with time.
start_time = time.perf_counter(): Gets the current value of a high-resolution performance counter before your program's main logic starts. This is the starting point for your time measurement.
try:: This block contains the main code you want to measure.
except Exception as e: (Optional but Recommended): Catches any exceptions that occur within the try block. This prevents the program from crashing immediately and allows the finally block to execute. You can log the error here.
finally:: This block always executes after the try block finishes, whether it finished successfully or an exception occurred (even if it was caught by except). This makes it the perfect place to:
end_time = time.perf_counter(): Get the value of the performance counter after your program's logic (or the error) finished.
duration = end_time - start_time: Calculate the difference between the end time and the start time to get the total elapsed time.
print(f"Program finished in {duration:.4f} seconds."): Print the calculated duration. The :.4f formats the output to 4 decimal places.
This pattern ensures that no matter how your program finishes (normally or with an error), you get the execution time printed just before the script exits.