Home > Backend Development > Python Tutorial > How Can I Accurately Measure the Execution Time of a Single Function Call in Python?

How Can I Accurately Measure the Execution Time of a Single Function Call in Python?

Mary-Kate Olsen
Release: 2024-12-15 09:16:10
Original
112 people have browsed it

How Can I Accurately Measure the Execution Time of a Single Function Call in Python?

Measuring Elapsed Time in Python

Measuring the execution time of a function is a common task in programming. Timeit is a useful module for measuring elapsed time, but it can be confusing to use.

The problem arises from the fact that timeit returns the time taken to execute a function multiple times. In the example provided, timeit will execute the print statement multiple times, which is not what you want.

To measure the elapsed time for a single execution, use time.time() instead. This function returns the current wall-clock time in seconds. You can measure the elapsed time by taking the difference between the start and end time.

Here's an example:

import time

start = time.time()
print("hello")
end = time.time()
elapsed_time = end - start

print(elapsed_time)  # Output: Time taken to print "hello" in seconds
Copy after login

In Python 3.3 or later, you can also use perf_counter() or process_time(), depending on your requirements. Before 3.3, time.clock() was recommended, but it has been deprecated.

The above is the detailed content of How Can I Accurately Measure the Execution Time of a Single Function Call in Python?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template