Skip to content

Instantly share code, notes, and snippets.

@wklchris
Created July 15, 2021 15:46
Show Gist options
  • Save wklchris/6848545194b65ee58f98dfead4c80458 to your computer and use it in GitHub Desktop.
Save wklchris/6848545194b65ee58f98dfead4c80458 to your computer and use it in GitHub Desktop.
Measure actual running time in Python 3

Measure actual running time with 'datetime' module

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.
  • Module datetime records the time duration between two timestamps in classtype of timedelta. However, this type of variable doesn't support strftime function.
    • So I decided to format the timedelta by myself.

Other methods that I don't like but may work for you:

Methods

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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment