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
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.
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.
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.
timeit moduleBest 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))"
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
| Method | Measures | Includes sleep | Use case |
|---|---|---|---|
time.perf_counter() | Wall-clock | ✅ | Most accurate timing |
time.time() | Wall-clock | ✅ | Real-world elapsed time |
time.process_time() | CPU time | ❌ | CPU-bound benchmarks |
timeit | Wall-clock | ✅ | Automated benchmarking |
datetime.now() | Wall-clock | ✅ | Simple readable timing |