python 实现简单的PerformanceCountCallHandler装饰器
Python的functools模块, 提供了3个有趣函数, partial, update_wrapper 和wraps 。
partial函数,它可以重新绑定函数的可选参数,生成一个callable的partial对象。
update_wrapper函数,把被封装函数的__name__、__module__、__doc__和 __dict__都复制到封装函数去。
wraps函数,对update_wrapper更进一步封装。
可以利用wraps函数,实现简单的方法拦截机制,来实现自己的PerformanceCountCallHandler,
具体实现:
#-*- coding: UTF-8 -*- #------------------------------------------------------------------------------- # Name: 模块2 # Purpose: # # Author: ankier # # Created: 22-12-2012 # Copyright: (c) Ankier 2012 # Licence: <2012~2020> #------------------------------------------------------------------------------- import time from functools import wraps _Cache ={} def PerformanceCountCallHandler(): def _PerformanceCountCallHandler(fun): @wraps(fun) def wrap(args, kw): glos = fun.func_globals package = glos['__package__'] model = glos['__name__'] methodName = fun.func_name timeStart = time.time() result = fun(args, kw) timeEnd = time.time() print 'package:',package,' , model:', model, ' , methodName:',methodName,'. ', timeEnd - timeStart, 's' return result return wrap return _PerformanceCountCallHandler
import time from cacheCallHandler import CacheCallHandler from performanceCountCallHandler import PerformanceCountCallHandler @CacheCallHandler() @PerformanceCountCallHandler() def Sum(xx , yy ): sum = xx + yy print '------sum----- ' time.sleep(10) return sum print Sum(4, 5) print Sum(4, 5)
import time from cacheCallHandler import CacheCallHandler from performanceCountCallHandler import PerformanceCountCallHandler @PerformanceCountCallHandler() @CacheCallHandler() def Sum(xx , yy ): sum = xx + yy print '------sum----- ' time.sleep(10) return sum print Sum(4, 5) print Sum(4, 5)
运行结果
------sum----- file = /root/workspace/study/source/cacheCallHandler/cacheCallHandler.py , method = Sum , performance count (s): 10.0078930855 s 9 file = /root/workspace/study/source/cacheCallHandler/cacheCallHandler.py , method = Sum , performance count (s): 6.8187713623e-05 s 9