Python implements a timer to count the running time

ponponon
中文

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
阅读 734

python后端实战经验分享
Python来自荷兰,面向未来

Python 后端工程师可加:企鹅群:537131912

1.5k 声望
36 粉丝
0 条评论

Python 后端工程师可加:企鹅群:537131912

1.5k 声望
36 粉丝
文章目录
宣传栏