chore: 移除 euler_56 中未使用的 MAX_EMAX 导入并添加 euler_57 基准测试装饰器
This commit is contained in:
40
solutions/0057.SquareRoot/euler_57.py
Normal file
40
solutions/0057.SquareRoot/euler_57.py
Normal file
@@ -0,0 +1,40 @@
|
||||
'''
|
||||
|
||||
'''
|
||||
import time
|
||||
from functools import wraps
|
||||
from typing import Any, Callable, TypeVar
|
||||
|
||||
F = TypeVar("F", bound=Callable[..., Any])
|
||||
|
||||
|
||||
def benchmark(repeat: int = 1) -> Callable[[F], F]:
|
||||
if repeat < 1:
|
||||
raise ValueError("repeat must >= 1")
|
||||
|
||||
def decorator(func: F) -> F:
|
||||
@wraps(func)
|
||||
def wrapper(*args: Any, **kwargs: Any) -> Any:
|
||||
total = 0.0
|
||||
result = None
|
||||
|
||||
for _ in range(repeat):
|
||||
start = time.perf_counter()
|
||||
result = func(*args, **kwargs)
|
||||
end = time.perf_counter()
|
||||
total += end - start
|
||||
|
||||
wrapper.avg_time = total / repeat # type: ignore[attr-defined]
|
||||
wrapper.total_time = total # type: ignore[attr-defined]
|
||||
|
||||
print(
|
||||
f"[Benchmark] {func.__name__} | repeated {repeat} times | "
|
||||
f"average: {wrapper.avg_time:.6f}s | total: {wrapper.total_time:.6f}s" # type: ignore[attr-defined]
|
||||
)
|
||||
return result
|
||||
|
||||
wrapper.avg_time = 0.0 # type: ignore[attr-defined]
|
||||
wrapper.total_time = 0.0 # type: ignore[attr-defined]
|
||||
return wrapper # type: ignore[return-value]
|
||||
|
||||
return decorator
|
||||
Reference in New Issue
Block a user