一.统计函数运行时间
import functools
import time
def wrap_performance(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
t_begin = time.time()
result = func(self, *args, **kwargs)
t_end = time.time()
print("Time: %f " % (t_end - t_begin))
return result
return wrapper
class Test:
def __init__(self):
pass
@wrap_performance
def test(self):
time.sleep(1)
t = Test()
t.test()
二.插入日志
def wrap_logger(func):
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
print ("%s(%s, %s)" % (func, args, kwargs))
print "before execute"
result = func(self, *args, **kwargs)
print "after execute"
return result
return wrapper
class Test:
def __init__(self):
pass
@wrap_logger
def test(self, a, b, c):
print a, b, c
t = Test()
t.test(1, 2, 3)
来源:优快云
原文:https://blog.youkuaiyun.com/kongxx/article/details/51654751
版权声明:本文为博主原创文章,转载请附上博文链接!
本文介绍Python中使用装饰器进行函数运行时间和日志记录的方法。通过装饰器,可以方便地为函数添加统计运行时间及日志记录的功能,无需修改函数内部代码。
281

被折叠的 条评论
为什么被折叠?



