To time a function and print the duration in Python, we can use the time
module. Here's how to do it:
main.py202 chars12 lines
In this code, we first import the time
module. We then define our function my_function()
. To time this function, we use start_time = time.time()
to get the current time, run our function my_function()
, and then get the current time again with end_time = time.time()
. We then subtract the start time from the end time to get the duration of the function in seconds.
Finally, we print out the duration using print("Function took", duration, "seconds to run.")
. This will output a message like "Function took 0.5 seconds to run." (assuming the duration is 0.5 seconds).
gistlibby LogSnag