首页 > 图灵资讯 > 技术篇>正文

函数获取自身的函数名字 + 函数运行时间计算和统计

2023-06-20 09:31:28

1.函数

import sysclass calcount01:    def __init__(self, func):        self.func = func        self.call_num = 0    def __call__(self, *args, **kwargs):        self.call_num += 1        print('self.call_num is: {} {}'.format(self.call_num, self.func.__name__))  #这是使用类装饰器的方法        return self.func(*args, **kwargs)@calcount01deff call_test():    print('----- in call_test, my func name: {}'.format(sys._getframe().f_code.co_name))   #这是第二个call_test()call_test()

2.计算函数运行时间和统计

# todo: record the real runtine by use this decoratorimport timeimport functoolsdef my_decorator(func):    print('begin my_decorator')    @functools.wraps(func)    def my_wrapper(*args, **kwargs):        print('begin my_wrapper')        start_time = time.perf_counter()        func(*args, **kwargs)        end_time = time.perf_counter()        print('function: {} , runtime: {} .'.format(func.__name__, (end_time - start_time)))    return my_wrapper@my_decorator   ### 在定义函数之前,用这个装饰器装饰,deff可以统计函数的运行时间 greet(name):    print('hello from greet: {}'.format(name))    time.sleep(3)greet('xiaowei')print(greet.__name__)

用一个例子演示会更清晰

上一篇 用python编写exporter监控接口访问数量+错误率+响应时间
下一篇 tcp三次握手 - 四次断开

文章素材均来源于网络,如有侵权,请联系管理员删除。