💡 Python QuickBits — ⏱️ Benchmarking with timeit
Posted On: October 15, 2025
Description:
Ever wondered which piece of code runs faster?
The timeit module lets you benchmark small snippets of Python code accurately. It automatically runs them multiple times and reports total execution time — perfect for comparing different approaches.
📝 Compare String Concatenation Methods
Let’s compare two common string concatenation techniques — using "+" in a loop vs. "".join() with a list.
import timeit
setup_code = "words = ['python', 'is', 'fast'] * 1000" # sample data
# Using '+'
concat_test = """
result = ''
for w in words:
result += w
"""
# Using join()
join_test = """
result = ''.join(words)
"""
t_concat = timeit.timeit(concat_test, setup=setup_code, number=1000)
t_join = timeit.timeit(join_test, setup=setup_code, number=1000)
print(f"String '+' concatenation: {t_concat:.4f}s")
print(f"String join(): {t_join:.4f}s")
print(f"join() is roughly {t_concat / t_join:.1f}x faster")
Here, timeit.timeit() runs the given snippet (number times) and returns total seconds taken.
You’ll typically find that join() is 5–10× faster than + for large strings.
⚙️ Quick One-Liner
You can benchmark any small snippet directly from the command line too:
python -m timeit "'-'.join(['a'] * 1000)"
It automatically repeats the snippet and prints the average execution time.
✅ Key Points
- ✅ Use timeit to measure performance accurately.
- ✅ Run multiple iterations for consistent results.
- ✅ Great for comparing small, isolated snippets.
- 🐍 Available in Python’s standard library — no extra installs.
Code Snippet:
import timeit # module for precise code benchmarking
# Define two setup snippets as strings
setup_code = "words = ['python', 'is', 'fast'] * 1000" # simulate repeated text
# Method 1: string concatenation with '+'
concat_test = """
result = ''
for w in words:
result += w
"""
# Method 2: efficient join
join_test = """
result = ''.join(words)
"""
# Run benchmarks — timeit.timeit() runs the code many times and returns total seconds
t_concat = timeit.timeit(concat_test, setup=setup_code, number=1000)
t_join = timeit.timeit(join_test, setup=setup_code, number=1000)
print(f"String '+' concatenation: {t_concat:.4f}s")
print(f"String join(): {t_join:.4f}s")
print(f"join() is roughly {t_concat / t_join:.1f}x faster")
Link copied!
Comments
Add Your Comment
Comment Added!
No comments yet. Be the first to comment!