Skip to content

Instantly share code, notes, and snippets.

@Hammer2900
Created October 18, 2025 08:02
Show Gist options
  • Select an option

  • Save Hammer2900/18d2e4fcf984af9b6862b69e45d87bb6 to your computer and use it in GitHub Desktop.

Select an option

Save Hammer2900/18d2e4fcf984af9b6862b69e45d87bb6 to your computer and use it in GitHub Desktop.
umpacking test speed
import timeit
from dataclasses import dataclass, replace
# ============================================================
# Исходные данные
# ============================================================
color = (0, 121, 241, 255)
new_alpha = 128
EXPECTED = (0, 121, 241, 128)
# ============================================================
# Методы
# ============================================================
def method_slice_concat():
return color[:3] + (new_alpha,)
def method_list_conversion():
lst = list(color)
lst[-1] = new_alpha
return tuple(lst)
def method_unpacking():
r, g, b, a = color
return (r, g, b, new_alpha)
def method_enumerate():
return tuple(new_alpha if i == 3 else v for i, v in enumerate(color))
def method_dataclass():
@dataclass(frozen=True)
class Color:
r: int
g: int
b: int
a: int
color_obj = Color(*color)
new_color_obj = replace(color_obj, a=new_alpha)
return (new_color_obj.r, new_color_obj.g, new_color_obj.b, new_color_obj.a)
# ============================================================
# Проверка корректности
# ============================================================
methods = [
method_slice_concat,
method_list_conversion,
method_unpacking,
method_enumerate,
method_dataclass,
]
for fn in methods:
result = fn()
assert result == EXPECTED, f"{fn.__name__} failed: got {result}"
# ============================================================
# Тест скорости
# ============================================================
def bench(fn, number=1000):
t = timeit.timeit(fn, number=number)
return t
results = [(fn.__name__, bench(fn)) for fn in methods]
results.sort(key=lambda x: x[1])
# ============================================================
# Вывод результатов
# ============================================================
print("=== Speed Test: Tuple Alpha Modification ===")
print(f"{'Method':<30} | {'Time (sec)':>12}")
print("-" * 45)
for name, t in results:
print(f"{name:<30} | {t:>12.6f}")
print("-" * 45)
print(f"Fastest: {results[0][0]} 🚀")
# ============================================================
# Пример вывода:
# ============================================================
# === Speed Test: Tuple Alpha Modification ===
# Method | Time (sec)
# ---------------------------------------------
# method_unpacking | 0.120345
# method_slice_concat | 0.132874
# method_list_conversion | 0.188421
# method_enumerate | 0.354129
# method_dataclass | 1.982321
# ---------------------------------------------
# Fastest: method_unpacking 🚀
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment