Advertisement
Guest User

Measure execution time of python functions

a guest
Aug 25th, 2016
78
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.02 KB | None | 0 0
  1. import os
  2. import functools
  3. import inspect
  4. import logging
  5. import time
  6.  
  7. logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG)
  8. logger = logging.getLogger(__name__)
  9. logger.level = logging.DEBUG
  10.  
  11. ENABLE_TIMERS = True
  12. _LOG_STRING = 'Timed function call: %s (%s) with args "%s" took %s seconds'
  13.  
  14.  
  15. def _logging_wrapper(func, func_name, func_file, bind=None):
  16.     @functools.wraps(func)
  17.     def _wrapper(*args, **kwargs):
  18.         if bind:
  19.             func_args = inspect.getcallargs(func, bind, *args, **kwargs)
  20.             start_time = time.clock()
  21.             result = func(bind, *args, **kwargs)
  22.         else:
  23.             func_args = inspect.getcallargs(func, *args, **kwargs)
  24.             start_time = time.clock()
  25.             result = func(*args, **kwargs)
  26.         duration = time.clock() - start_time
  27.  
  28.         logger.debug(_LOG_STRING % (func_name, func_file, func_args, duration))
  29.         return result
  30.     return _wrapper
  31.  
  32.  
  33. class _DescriptorWrapper(object):
  34.     def __init__(self, func):
  35.         self.func = func
  36.         self.func_file = os.path.join(os.getcwd(), inspect.getfile(self.func))
  37.         self.func_module = inspect.getmodule(self.func).__name__
  38.  
  39.     def __get__(self, instance, owner):
  40.         func_name = '.'.join((self.func_module, owner.__name__,
  41.                               self.func.__name__))
  42.         return _logging_wrapper(self.func, func_name, self.func_file,
  43.                                 bind=instance)
  44.  
  45.     def __call__(self, *args, **kwargs):
  46.         func_name = '.'.join((self.func_module, self.func.__name__))
  47.         return _logging_wrapper(self.func, func_name,
  48.                                 self.func_file)(*args, **kwargs)
  49.  
  50.  
  51. def logexectime(func):
  52.     if not ENABLE_TIMERS or inspect.isbuiltin(func):
  53.         return func
  54.     return functools.wraps(func)(_DescriptorWrapper(func))
  55.  
  56.  
  57. class A(object):
  58.  
  59.     @logexectime
  60.     def f1(self, a, b):
  61.         return a + b
  62.  
  63.  
  64. @logexectime
  65. def f2(a, b):
  66.     print a + b
  67.  
  68. a = A()
  69. print a.f1(10, 12)
  70. f2(45, 12)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement