Use metaclass to implement AOP-style profiler

Source: Internet
Author: User
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! :)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.