Measuring Python Execution Time with the time Module
Measuring Python Execution Time with the time Module ⏱️
When you're optimizing code or comparing algorithms, measuring execution time is essential.
Python's built-in time module makes it easy to track performance using time.time().
✅ Basic Execution Time Measurement
Record time before and after your code block, and calculate the difference.
import time
start = time.time()
# Code to measure
for _ in range(1000000):
pass
end = time.time()
print(f"Execution Time: {end - start:.4f} seconds")
✅ Performance Comparison Example
Compare list creation using comprehension vs. for-loop with append.
# Comparing list creation methods
import time
start = time.time()
a = [i for i in range(1000000)]
end = time.time()
print("List comprehension:", end - start)
start = time.time()
b = []
for i in range(1000000):
b.append(i)
end = time.time()
print("For-loop append:", end - start)
time.time() returns a float in seconds and is accurate enough for most basic timing needs.
For more precise benchmarking, you can also explore time.perf_counter().
If you can’t measure it, you can’t improve it. Start timing, start optimizing — and build faster, smarter code. ๐
Icons by Flaticon
Comments
Post a Comment