Skip to content

Instantly share code, notes, and snippets.

@linkerlin
Last active December 18, 2015 05:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save linkerlin/5734206 to your computer and use it in GitHub Desktop.
Save linkerlin/5734206 to your computer and use it in GitHub Desktop.
Python的计时用metaclass 。演示了Meta Class的用法。
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