user
How to measure elapsed time in Python?
alphonsio

In Python, you can measure elapsed time (how long a piece of code takes to run) in several ways — the most common and accurate method is using the time or timeit module.

Here are the main approaches


1. Using time.perf_counter() (Recommended)

This is the best general-purpose timer for measuring short durations because it has high resolution and includes time spent during sleep.

import time

start = time.perf_counter()  # Start timer

# --- your code here ---
time.sleep(1.5)

end = time.perf_counter()    # End timer
elapsed = end - start

print(f"Elapsed time: {elapsed:.4f} seconds")

Use this for: benchmarking code execution, performance measurement, or profiling.


2. Using time.time()

This gives the current wall-clock time (seconds since the epoch). It’s less precise than perf_counter() but still works fine for simple measurements.

import time

start = time.time()

# --- your code here ---
time.sleep(2)

end = time.time()
print(f"Elapsed time: {end - start:.4f} seconds")

Use this for: timing long-running tasks, real-world elapsed time.


3. Using time.process_time()

This measures CPU time used by your program — it excludes sleep or time spent waiting for I/O.

import time

start = time.process_time()

# --- your code here ---
time.sleep(2)  # won't count this time
for _ in range(10**7):
    pass

end = time.process_time()
print(f"CPU time: {end - start:.4f} seconds")

Use this for: measuring CPU performance or benchmarking algorithms.


4. Using timeit module

Best for precise benchmarking of small code snippets — it automatically handles repetitions and reduces noise.

import timeit

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

You can also use it directly from the command line:

python -m timeit "sum(range(1000))"

5. Using datetime (for readability)

Good for logging or timestamps, not ideal for benchmarking.

from datetime import datetime
start = datetime.now()

# --- your code here ---
time.sleep(1)

elapsed = datetime.now() - start
print(f"Elapsed time: {elapsed}")

Summary Table

MethodMeasuresIncludes sleepUse case
time.perf_counter()Wall-clockMost accurate timing
time.time()Wall-clockReal-world elapsed time
time.process_time()CPU timeCPU-bound benchmarks
timeitWall-clockAutomated benchmarking
datetime.now()Wall-clockSimple readable timing