需求: 系統中的每個操作流程,需要列印所有被執行到的方法的耗時。
實現原理,利用python的元類型編程,動態改變class的建立過程,攔截class的方法,加上自訂的耗時記錄。把記錄匯出到csv檔案裡面,方便對資料進行刪選和排序。
具體代碼實現:
#-*- coding: UTF-8 -*-#-------------------------------------------------------------------------------# Name: performanceCountMeta# Purpose: 記錄每個方法的時間消耗,協助程式員方便的尋找系統的效能瓶頸## Author: ankier## Created: 26-01-2013# Copyright: (c) ankier 2013# Licence: <your licence>#-------------------------------------------------------------------------------from types import FunctionTypeimport time, datetimeimport csv pfile = file('E:\performanceCount.csv', 'ab')writer = csv.writer(pfile)writer.writerow(['Module', 'method', 'spend time', 'time Start', 'time End'])pfile.close()## @summary: wrap 方法,AOP實現,記錄每個函數的執行時間def _RecordPerformance(func): def warp(*args): glos = func.func_globals model = glos['__name__'] methodName = func.func_name #Start time starTime = time.time() startStr = datetime.datetime.now().isoformat() result = func(*args) #End time endTime = time.time() endStr = datetime.datetime.now().isoformat() SpendTime = endTime - starTime row = [model, methodName, str(SpendTime), startStr, endStr] pfile = file('E:\performanceCount.csv', 'ab') writer = csv.writer(pfile) writer.writerow(row) pfile.close() return result return warp ## @summary: 效能計數器的元類型,動態修改類的建立過程,wrap 一些特定的方法。實現方法攔截,記錄效能class PerformanceCountMeta(type): def __new__(cls, name, bases, dct): for name, value in dct.iteritems(): if name not in ('__metaclass__', '__init__', '__module__') and \ type(value) == FunctionType: value = _RecordPerformance(value) dct[name] = value return type.__new__(cls, name, bases, dct)
例子如何使用,
## @summary: word host 視窗class WordHostWindow(wx.Window): __metaclass__ = PerformanceCountMeta def __init__(self, parent): wx.Window.__init__(self, parent)
運行結果: