Python

Banco de pruebas timeit: 3 implementaciones cara a cara

Compara tres formas de sumar 100 000 enteros con timeit.repeat (minimo de 5 repeticiones), y luego clasifica los candidatos por ms/llamada con ratio y barras.

Requisitos

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))

Resultado

implémentation   ms/appel   ratio
--------------------------------------
sum() natif         0.412    1.0x  ▇▇▇
boucle for          2.087    5.1x  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇
genexp + sum        3.295    8.0x  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇
timeitPerformanceBenchmarkProfiling

Snippets relacionados

Volver al Data Lab