Skip to content

python装饰器decorator #2

@littlemoon-zh

Description

@littlemoon-zh

A time_cost decorator for both common functions and coroutine functions, using wraps in functools module.

import asyncio
import time
from functools import wraps


def time_cost(fn):
    if asyncio.iscoroutinefunction(fn):
        @wraps(fn)
        async def wrapper(*args, **kwargs):
            start = time.time_ns()
            res = await fn(*args, **kwargs)
            print(f'func {fn.__name__} costs {(time.time_ns() - start) / 1e6:.2f} ms')
            return res

        return wrapper
    else:
        @wraps(fn)
        def wrapper(*args, **kwargs):
            start = time.time_ns()
            res = fn(*args, **kwargs)
            print(f'func {fn.__name__} costs {(time.time_ns() - start) / 1e6:.2f} ms')
            return res

        return wrapper

How does it work:

  • TODO

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions