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
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!