Skip to content

Instantly share code, notes, and snippets.

@snelis
Created February 4, 2014 13:31
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 snelis/8803605 to your computer and use it in GitHub Desktop.
Save snelis/8803605 to your computer and use it in GitHub Desktop.
import functools
def time_execution(function=None, *args, **kwargs):
"""
Time the execution of a method.
If the optional kwargs contain the warning or error threshold, log it if it exceeds it.
"""
print 'args', args
print 'kwargs', kwargs
def wrapper_factory(func):
@functools.wraps(func)
def wrapper(*args, **kwargs):
response = func(*args, **kwargs)
return response
return wrapper
if function:
return wrapper_factory(function)
return wrapper_factory
class MyClass(object):
def inline(self, method):
return method
@time_execution
def simple(self, method):
""" simple doc """
return method
@time_execution(adv=True)
def adv(self, method):
""" adv doc """
return method
cls = MyClass()
print '-'*50
print time_execution(inline=True)(cls.inline)('hello world inline')
print '-'*50
print cls.simple('hello world simple')
print cls.simple.__name__, cls.simple.__doc__
print '-'*50
print cls.adv('hello world adv')
print cls.adv.__name__, cls.adv.__doc__
print '-'*50
@time_execution(regular_func=True)
def hello_world(*args, **kwargs):
""" regular func """
print args, kwargs
hello_world('regular function')
print hello_world, hello_world.__doc__
print '-'*50
def hello_world(*args, **kwargs):
print args, kwargs
time_execution(inline_regular_func=True)(hello_world)('regular function')
@snelis
Copy link
Author

snelis commented Feb 4, 2014

args ()
kwargs {}
args ()
kwargs {'adv': True}
--------------------------------------------------
args ()
kwargs {'inline': True}
hello world inline
--------------------------------------------------
hello world simple
simple  simple doc 
--------------------------------------------------
hello world adv
adv  adv doc 
--------------------------------------------------
args ()
kwargs {'regular_func': True}
('regular function',) {}
<function hello_world at 0x10d40fe60>  regular func 
--------------------------------------------------
args ()
kwargs {'inline_regular_func': True}
('regular function',) {}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment