We implement the timer in two ways.

  • Decorator implements a timer
  • Builder implements a timer

Decorator implements a timer

import time


def timer_dec(func):
    def inner(*args, **kwargs):
        start = time.time()
        ret_val = func(*args, **kwargs)
        end = time.time()
        print(f'pay time is {end-start} s')
        return ret_val
    return inner


@timer_dec
def haha():
    print('笑死我了')
    time.sleep(0.01)


haha()

output result

笑死我了
pay time is 0.010136842727661133 s

Builder implements a timer

The implementation of the generator method requires the help of the Python built-in library contextlib.

It's not that contextlib must be used, but contextlib can be more elegant
You can refer to: the usage of with in python, context manager
from contextlib import contextmanager

def haha():
    print('笑死我了')
    time.sleep(0.01)


@contextmanager
def timer_gen():
    start = time.time()
    yield
    end = time.time()
    print(f'pay time is {end-start} s')


with timer_gen():
    haha()

output result

笑死我了
pay time is 0.010103464126586914 s

universe_king
3.4k 声望680 粉丝