How do I measure elapsed time in Python?

29    Asked by kalylc_9210 in Python , Asked on May 20, 2025

Measuring elapsed time in Python is essential for performance testing or benchmarking. But what’s the best way to do it — and how accurate is it across different methods?

Answered by Lucas Jackson

Measuring elapsed time in Python is quite straightforward and useful, especially when you're optimizing your code or trying to understand how long certain operations take. Python provides several ways to do this depending on how precise you need the timing to be.

Common Methods to Measure Time:

Using time module:

import time
start = time.time()
# your code here
end = time.time()
print(f"Elapsed time: {end - start} seconds")

  • Good for general timing.
  • Measures wall-clock time.
  • Simple and easy to understand.

Using time.perf_counter():

import time
start = time.perf_counter()
# your code here
end = time.perf_counter()
print(f"Elapsed time: {end - start} seconds")
More precise than time.time().

Ideal for benchmarking smaller code segments.

Using datetime module:

from datetime import datetime
start = datetime.now()
# your code here
end = datetime.now()
print(f"Elapsed time: {end - start}")

  • Returns a timedelta object.
  • Useful when you want formatted date-time output along with duration.

Using timeit module (for very precise benchmarking):

import timeit
elapsed = timeit.timeit("sum(range(1000))", number=1000)
print(f"Elapsed time: {elapsed} seconds")

  • Best for performance testing small code snippets.
  • Runs the code multiple times to get accurate results.

Final Tip:

Choose your method based on what you’re timing — for general usage, time or datetime is enough. For precise performance checks, go with perf_counter() or timeit().



Your Answer

Interviews

Parent Categories