Micro-Benchmarking with timeit
Never use `time.time()` to measure quick operations. The `timeit` module runs code thousands of times, disabling garbage collection for precision measurements ⏱️.
import timeit
# Compare list comprehension vs map():
comp_time = timeit.timeit("[x * 2 for x in range(100)]", number=10000)
map_time = timeit.timeit("list(map(lambda x: x * 2, range(100)))", number=10000)
print(f"Comprehension: {comp_time:.4f}s ⏱️")
print(f"Map + Lambda: {map_time:.4f}s ⏱️")
# 81. Micro-Benchmarking with timeit Never use `time.time()` to measure quick operations. The `timeit` module runs code thousands of times, disabling garbage collection for precision measurements ⏱️. ```python import timeit # Compare list comprehension vs map(): comp_time = timeit.timeit("[x * 2 for x in range(100)]", number=10000) map_time = timeit.timeit("list(map(lambda x: x * 2, range(100)))", number=10000) print(f"Comprehension: {comp_time:.4f}s ⏱️") print(f"Map + Lambda: {map_time:.4f}s ⏱️") ``` `timeit` avoids pitfalls like system clock resolution limits, background OS interruptions, and GC pauses by running isolated iterations! ⏱️ --- ### Question Why is `timeit.timeit()` superior to manual `time.time()` diffs for benchmarking small functions? 🧠 - [ ] a. It runs repeated iterations and disables background interference to ensure statistical accuracy ⏱️ - [ ] b. It compiles Python into machine code before running - [ ] c. It runs the code in an isolated AWS Lambda instance - [ ] d. It automatically optimizes the Python AST --- ### Challenge Import `timeit`. Use `timeit.timeit('"-".join(str(n) for n in range(10))', number=100)`. Print whether the elapsed time is greater than `0`. 🎯 <details> <summary>Solution</summary> ```python import timeit elapsed = timeit.timeit("'-'.join(str(n) for n in range(10))", number=100) print(elapsed > 0) ``` </details>