python 實現簡單的PerformanceCountCallHandler裝飾器

來源:互聯網
上載者:User

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 timefrom 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 timefrom cacheCallHandler import CacheCallHandlerfrom performanceCountCallHandler import PerformanceCountCallHandler@CacheCallHandler()@PerformanceCountCallHandler()def Sum(xx , yy ):    sum = xx + yy    print '------sum----- '    time.sleep(10)                return sumprint Sum(4, 5)print Sum(4, 5)
import timefrom cacheCallHandler import CacheCallHandlerfrom performanceCountCallHandler import PerformanceCountCallHandler@PerformanceCountCallHandler()@CacheCallHandler()def Sum(xx , yy ):    sum = xx + yy    print '------sum----- '    time.sleep(10)                return sumprint Sum(4, 5)print Sum(4, 5)

運行結果

------sum----- file =  /root/workspace/study/source/cacheCallHandler/cacheCallHandler.py , method =  Sum ,  performance count (s): 10.0078930855 s9file =  /root/workspace/study/source/cacheCallHandler/cacheCallHandler.py , method =  Sum ,  performance count (s): 6.8187713623e-05 s9

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.