time a function and print the duration in python

To time a function and print the duration in Python, we can use the time module. Here's how to do it:

main.py
import time

def my_function():
    # code goes here

start_time = time.time()
my_function()
end_time = time.time()

duration = end_time - start_time
print("Function took", duration, "seconds to run.")
202 chars
12 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