timeit benchmark: 3 implementations head to head
Compares three ways to sum 100,000 integers with timeit.repeat (minimum of 5 repeats), then ranks the candidates by ms/call with ratios and bars.
Prerequisites
Python 3.9+ (bibliothèque standard)
Python
import timeit
setup = "data = list(range(100_000))"
candidats = {
"boucle for": "s = 0\nfor x in data: s += x",
"sum() natif": "s = sum(data)",
"genexp + sum": "s = sum(x for x in data)",
}
mesures = {
nom: min(timeit.repeat(code, setup, number=200, repeat=5)) / 200 * 1e3
for nom, code in candidats.items()
}
reference = min(mesures.values())
print(f"{'implémentation':<15} {'ms/appel':>9} {'ratio':>7}")
print("-" * 38)
for nom, ms in sorted(mesures.items(), key=lambda x: x[1]):
print(f"{nom:<15} {ms:>9.3f} {ms / reference:>6.1f}x "
+ "▇" * round(ms / reference * 3))Result
implémentation ms/appel ratio -------------------------------------- sum() natif 0.412 1.0x ▇▇▇ boucle for 2.087 5.1x ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ genexp + sum 3.295 8.0x ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇
timeitPerformanceBenchmarkProfiling