Skip to content

Instantly share code, notes, and snippets.

@messa
Last active January 12, 2016 13:49
Show Gist options
  • Save messa/2cce397aa6db08de4f56 to your computer and use it in GitHub Desktop.
Save messa/2cce397aa6db08de4f56 to your computer and use it in GitHub Desktop.
import logging
from time import monotonic as monotime
logger = logging.getLogger(__name__)
class TimingWrapper:
'''
Wrapper na jakoukoli strukturu objektů, který měří dobu trvání běhu metod
a loguje, pokud tato doba překoná nastavený limit.
Momentálně teda použito na MongoDB, protože pomalé operace většinou ukazují
na nedostatečné indexy.
'''
_threshold = 0.1
def __init__(self, obj, prefix=''):
self._obj = obj
self._prefix = prefix
def __getattr__(self, name):
return TimingWrapper(getattr(self._obj, name), prefix=self._prefix + '.' + name)
def __getitem__(self, name):
return TimingWrapper(self._obj[name], prefix=self._prefix + '[' + name + ']')
def __call__(self, *args, **kwargs):
t0 = monotime()
try:
return self._obj(*args, **kwargs)
finally:
td = monotime() - t0
if td > self._threshold:
logger.warning('%s(*%s, **%s) took %.3f s', self._prefix, args, kwargs, td)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment