How Do You Get Python to Compute How Long Something Took?

Problem scenario
You want to check the runtime duration of a section of Python code. How do you compute the amount of time something took in Python?

Solution
Write a program like this:

import datetime, time
t1 = datetime.datetime.now()
time.sleep(5)     # replace this line with the section of code you want to time
t2 = datetime.datetime.now()
t3 = t2 - t1
print("Time format is in hours:minutes:seconds:seconds_decimals")
print(t3)

Leave a comment

Your email address will not be published. Required fields are marked *