Last active
December 18, 2015 05:39
-
-
Save linkerlin/5734206 to your computer and use it in GitHub Desktop.
Python的计时用metaclass 。演示了Meta Class的用法。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
for attr, value in dict.iteritems(): | |
if isinstance(value, FunctionType): | |
dict[attr] = timing(value) | |
return super(Profiler, mcl).__new__(mcl, name, bases, dict) | |
class A(object): | |
__metaclass__ = Profiler | |
def foo(self): | |
total = 0 | |
for i in range(100000): | |
total = total+1 | |
print total | |
def foo2(self): | |
from time import sleep | |
total = 0 | |
for i in range(100000): | |
total = total+1 | |
sleep(0.0001) | |
print total | |
def main(): | |
a = A() | |
a.foo() | |
a.foo2() | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment