python 元类型编程,实现方法级的时间性能记录(performanceCount)

需求: 系统中的每个操作流程,需要打印所有被执行到的方法的耗时。

实现原理,利用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 FunctionType
import time, datetime
import 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)    

运行结果:

 

 

posted on 2013-01-26 20:57  |残阳|露  阅读(377)  评论(0编辑  收藏  举报

导航