zoukankan      html  css  js  c++  java
  • 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

     

  • 相关阅读:
    .NET程序员面试小技巧
    .ashx一般处理程序
    地铁线路图的设计与实现
    BS与CS的区别
    关于sqlserver2005异地自动备份
    二问唐骏:究竟是打工好还是创业好
    再燃中国激情 “创业指南针”团队首推创业专著
    读者看《赢道:成功创业者的28条戒律》
    创业必看:中国八大草根富豪发家史
    让你快乐,是我恒久写诗的唯一目的
  • 原文地址:https://www.cnblogs.com/ankier/p/2829075.html
Copyright © 2011-2022 走看看