To time a function in Python, you can use the time module. The time module provides a perf_counter() function that returns the number of seconds that have elapsed since an arbitrary time (usually when the program started). You can call this function twice, once before and once after the function you want to time, and then subtract the two values to get the elapsed time.
Here's an example of how to time a function using the time module:
import timedef my_function(): # Code to be timed here passstart_time = time.perf_counter()my_function()end_time = time.perf_counter()elapsed_time = end_time - start_timeprint(f"Elapsed time: {elapsed_time:.6f} seconds") |
In this example, the my_function() function is the function you want to time. The start_time variable is assigned the current value of perf_counter() before calling the function. The end_time variable is assigned the current value of perf_counter() after calling the function. Finally, the elapsed_time variable is assigned the difference between end_time and start_time.
The print() statement at the end of the code will display the elapsed time in seconds with 6 decimal places.
Note that the perf_counter() function measures the elapsed time based on the system clock, which can be affected by other processes running on the system. For more accurate timing, you can use the process_time() function instead, which measures the CPU time used by the program.