chore: update 2026-04-22
This commit is contained in:
50
main.py
50
main.py
@@ -22,17 +22,49 @@ def add_newproblem(num: int, name: str | None = None) -> None:
|
||||
|
||||
'''
|
||||
import time
|
||||
from functools import wraps
|
||||
from typing import Any, Callable, TypeVar
|
||||
|
||||
F = TypeVar("F", bound=Callable[..., Any])
|
||||
|
||||
|
||||
def timer(func):
|
||||
def wrapper(*args, **kwargs):
|
||||
start_time = time.time()
|
||||
result = func(*args, **kwargs)
|
||||
end_time = time.time()
|
||||
elapsed_time = end_time - start_time
|
||||
print(f"{func.__name__} time: {elapsed_time:.6f} seconds")
|
||||
return result
|
||||
return wrapper
|
||||
def benchmark(repeat: int = 1) -> Callable[[F], F]:
|
||||
'''
|
||||
重复运行目标函数并计算平均耗时。
|
||||
|
||||
平均耗时会被存储在 wrapper.avg_time 和 wrapper.total_time 中,
|
||||
同时会打印到控制台。函数的返回值不受影响。
|
||||
'''
|
||||
if repeat < 1:
|
||||
raise ValueError("repeat 必须 >= 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__} | 重复 {repeat} 次 | "
|
||||
f"平均: {wrapper.avg_time:.6f}s | 总计: {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