How to Monitor the Execution Time of a Python Program
Measuring the execution time of a Python program is crucial for optimizing performance and identifying bottlenecks. While the timeit module is useful for benchmarking short code snippets, it falls short when it comes to timing an entire program. Here's a simple and effective solution for this task:
Step 1: Import the Time Module
import time
Step 2: Start the Clock
As the program starts, capture the current timestamp using the time.time() function:
start_time = time.time()
Step 3: Run Your Program
Execute the main logic of your program here.
Step 4: End the Clock
Once your program completes, record the end time:
end_time = time.time()
Step 5: Calculate Execution Time
Subtract the start time from the end time to obtain the execution time:
execution_time = end_time - start_time
Step 6 (Optional): Print Execution Time
For convenience, you can print the execution time to the console:
print("--- %s seconds ---" % execution_time)
Example Output:
Assuming your program takes about 0.76 seconds to run, the output will be:
--- 0.764891862869 seconds ---
This approach provides an accurate measurement of your program's runtime, helping you evaluate its efficiency and make informed optimizations.
The above is the detailed content of How Can I Accurately Measure the Total Execution Time of My Python Program?. For more information, please follow other related articles on the PHP Chinese website!