Home > Backend Development > Python Tutorial > How Can I Accurately Measure the Execution Time of a Python Program?

How Can I Accurately Measure the Execution Time of a Python Program?

DDD
Release: 2024-12-16 00:50:11
Original
490 people have browsed it

How Can I Accurately Measure the Execution Time of a Python Program?

Measuring Execution Time of a Python Program

To gauge the precise duration of a Python program's execution, particularly a command line program that demands extended runtime, the following strategies may be employed:

The timeit module offers an effective approach for timing concise code snippets. However, for whole program measurement, consider employing a more comprehensive solution:

import time

# Capture the program's start time
start_time = time.time()

# Execute the program's main function
main()

# Calculate and display the execution time
print("--- %s seconds ---" % (time.time() - start_time))
Copy after login

This method hinges on the assumption that your program consumes at least 0.1 seconds to execute. Moreover, it outputs the execution time in a human-readable format, making it convenient to analyze the program's performance:

--- 0.764891862869 seconds ---
Copy after login

The above is the detailed content of How Can I Accurately Measure the Execution Time of a Python Program?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template