In Python, you can use the timer() function from the timeit module to time the execution of a function. The timer() function provides a more accurate way of measuring the execution time of a function as it takes into account factors like CPU usage and system load.
Here's an example of how to use timer() to time a function:
import timeitdef my_function(): # Code to be timed here passelapsed_time = timeit.timeit(my_function, number=1000)print(f"Elapsed time: {elapsed_time:.6f} seconds") |
In this example, the my_function() function is the function you want to time. The timeit.timeit() function is called with the function to be timed as the first argument and the number parameter set to the number of times to execute the function (in this case, 1000 times).
The timeit.timeit() function returns the total execution time for the specified number of function calls. This value is then assigned to the elapsed_time variable.
The print() statement at the end of the code will display the elapsed time in seconds with 6 decimal places.
Note that the timeit module provides more advanced ways of timing code, such as measuring the average execution time over multiple runs and disabling garbage collection during timing. You can find more information in the Python documentation for the timeit module.