Known difficulties:
- Module
time
doesn't provide time operation. You can't doing "minus" between two timestamps.- Function
time.process_time()
can record the CPU running time (excluding sleep). This is for performance purpose, not for actual run.
- Function
- Module
datetime
records the time duration between two timestamps in classtype oftimedelta
. However, this type of variable doesn't supportstrftime
function.- So I decided to format the timedelta by myself.
Other methods that I don't like but may work for you:
- Define a decorator to help. This is useful when you define your main codes in a function like
main()
, but I don't like doing that because it introduces extra indentation. - Moduel
timeit
is also helpful when you have such a main function. See timeit: Python Documentation for details. - Customize a
timing.py
and import it. See this StackOverflow answer: Nicojo's Answer to question: How do I get time of a Python program's execution?. - On Linux/Mac OS, there is a command called
time
. Use it like:time python test.py
Actual running time doesn't require accuracy that much, so I think datetime
module is OK. We first record the time before the main body, then record it again after executing the main boday, and finally format the string for printing.
from datetime import datetime
time_start = datetime.now()
# --- Main code body that needs measuring. For example:
# import time
# time.sleep(3)
time_end = datetime.now()
dt = str(time_end - time_start).split('.')[0] # trim microseconds
print(f"Duration: {dt} (from {time_start:%H:%M:%S} to {time_end:%H:%M:%S})")
Example output:
Duration: 0:00:05 (from 08:00:07 to 08:00:12)