The following is a piece of Python that implements profiler through metaclass. Code It is very simple and has few functions. It aims to display Python Meta
Programming's ability is undoubtedly very practical, and can bring the concept of aspect into play very well! The following profiler class (metaclass) can reuse the profiling of methods in different classes.
Class Profiler (type ):
Def _ New __ (MCL, name, bases, dict ):
From Time Import Clock
From Types Import Functiontype
Def Timing (func ):
Def Wrapper ( * ARGs, ** Kwds ):
Start = Clock ()
Value = Func ( * ARGs, ** Kwds)
End = Clock ()
Print Func. _ Name __ , ' Takes ' , (End - Start ), ' Seconds '
Return Value
Return Wrapper
ForATTR, ValueInDict. iteritems ():
IfIsinstance (value, functiontype ):
Dict [ATTR]=Timing (value)
ReturnSuper (profiler, MCL )._ New __(MCL, name, bases, dict)
ClassA (object ):
_ Metaclass __ =Profiler
Def Foo (Self ):
Total = 0
For I In Range ( 100000 ):
Total = Total + 1
Print Total
DefFoo2 (Self ):
FromTimeImportSleep
Total = 0
For I In Range ( 100000 ):
Total = Total + 1
Sleep ( 0.0001 )
Print Total
DefMain ():
A=A ()
A. Foo ()
A. foo2 ()
If _ Name __ = '_ Main __':
Main ()
I hope you can create more and more metaclass and share it with us! :)