python 实现简单的PerformanceCountCallHandler装饰器

本文介绍如何利用Python的functools模块中的partial, update_wrapper和wraps函数,实现性能计数和缓存调用的功能。通过简单的方法拦截机制,展示了如何创建PerformanceCountCallHandler和CacheCallHandler类,实现对函数调用的性能统计和数据缓存,以提高代码执行效率。

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

 

 

转载于:https://www.cnblogs.com/ankier/archive/2012/12/22/2829075.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值