|
1 | 1 | #!/usr/bin/env python3 |
2 | 2 | # -*- coding: utf-8 -*- |
| 3 | +import asyncio |
| 4 | +import functools |
| 5 | +import time |
| 6 | + |
3 | 7 | from math import ceil |
| 8 | +from typing import Any, Callable |
4 | 9 |
|
5 | 10 | from fastapi import FastAPI, Request, Response |
6 | 11 | from fastapi.routing import APIRoute |
7 | 12 |
|
8 | 13 | from backend.common.exception import errors |
| 14 | +from backend.common.log import log |
9 | 15 |
|
10 | 16 |
|
11 | 17 | def ensure_unique_route_names(app: FastAPI) -> None: |
@@ -34,3 +40,34 @@ async def http_limit_callback(request: Request, response: Response, expire: int) |
34 | 40 | """ |
35 | 41 | expires = ceil(expire / 1000) |
36 | 42 | raise errors.HTTPError(code=429, msg='请求过于频繁,请稍后重试', headers={'Retry-After': str(expires)}) |
| 43 | + |
| 44 | + |
| 45 | +def timer(func) -> Callable: |
| 46 | + """函数耗时计时装饰器""" |
| 47 | + |
| 48 | + @functools.wraps(func) |
| 49 | + async def async_wrapper(*args, **kwargs) -> Any: |
| 50 | + start_time = time.perf_counter() |
| 51 | + result = await func(*args, **kwargs) |
| 52 | + elapsed_seconds = time.perf_counter() - start_time |
| 53 | + _log_time(func, elapsed_seconds) |
| 54 | + return result |
| 55 | + |
| 56 | + @functools.wraps(func) |
| 57 | + def sync_wrapper(*args, **kwargs) -> Any: |
| 58 | + start_time = time.perf_counter() |
| 59 | + result = func(*args, **kwargs) |
| 60 | + elapsed_seconds = time.perf_counter() - start_time |
| 61 | + _log_time(func, elapsed_seconds) |
| 62 | + return result |
| 63 | + |
| 64 | + def _log_time(func, elapsed: float): |
| 65 | + # 智能选择单位(秒、毫秒、微秒、纳秒) |
| 66 | + if elapsed >= 1: |
| 67 | + unit, factor = 's', 1 |
| 68 | + else: |
| 69 | + unit, factor = 'ms', 1e3 |
| 70 | + |
| 71 | + log.info(f'{func.__module__}.{func.__name__} | {elapsed * factor:.3f} {unit}') |
| 72 | + |
| 73 | + return async_wrapper if asyncio.iscoroutinefunction(func) else sync_wrapper |
0 commit comments