Nono.MA

Measure Time Elapsed with Python

LAST UPDATED FEBRUARY 2, 2023

You can measure the time elapsed during the execution of Python commands by keeping a reference to the start time and then subtracting the current time at any point on your program from that start time to obtain the duration between two points in time.

from datetime import datetime
import time

# Define the start time.
start = datetime.now()

# Run some code..
time.sleep(2)

# Get the time delta since the start.
elapsed = datetime.now() - start
# datetime.timedelta(seconds=2, microseconds=005088)
# 0:00:02.005088

# Get the seconds since the start.
elapsed_seconds = elapsed.seconds
# 2

Let's create two helper functions to get the current time (i.e. now) and the elapsed time at any moment.

# Returns current time
# (and, if provided, prints the event's name)
def now(eventName = ''):
  if eventName:
    print(f'Started {eventName}..')
  return datetime.now()

# Store current time as `start`
start = now()

# Returns time elapsed since `beginning`
# (and, optionally, prints the duration in seconds)
def elapsed(beginning = start, log = False):
  duration = datetime.now() - beginning;
  if log:
    print(f'{duration.seconds}s')
  return duration

With those utility functions defined, we can measure the duration of different events.

# Define time to wait
wait_seconds = 2

# Measure duration (while waiting for 2 seconds)
beginning = now(f'{wait_seconds}-second wait.')

# Wait.
time.sleep(wait_seconds)

# Get time delta.
elapsed_time = elapsed(beginning, True)
# Prints 0:00:02.004004

# Get seconds.
elapsed_seconds = elapsed_time.seconds
# Prints 2

# Get microseconds.
elapsed_microseconds = elapsed_time.microseconds
# Prints 4004

Before you go

If you found this useful, you might want to join my mailing lists; or take a look at other posts about code, Python, React, and TypeScript.

BlogCodePythonTil