Skip to content

Instantly share code, notes, and snippets.

@ssoto
Last active October 11, 2017 14:45
Show Gist options
  • Save ssoto/39a93011c29e06db6282da2b843eb06b to your computer and use it in GitHub Desktop.
Save ssoto/39a93011c29e06db6282da2b843eb06b to your computer and use it in GitHub Desktop.
Benchmark decorator
import datetime
import logging
import importlib
import os
import traceback
import time
from timeit import default_timer as timer
def command_decorator(logger_obj):
if not(type(logger_obj) == logging.Logger):
raise Exception('Bad logger object passed')
else:
out_func = logger_obj.debug
def real_decorator(function):
def wrapped_function(*func_args, **func_kargs):
out_func('function args: %s' % str(func_args))
out_func('Starting...')
v = None
start = timer()
try:
v = function(*func_args, **func_kargs)
spent = timer() - start
out_func('Spent %.5f seconds' % spent)
out_func('Finished!')
except Exception as e:
out_func(e)
out_func(traceback.format_exc())
spent = timer() - start
out_func('Spent %.5f seconds' % spent)
finally:
return v
return wrapped_function
return real_decorator
from usefull_decorators import command_decorator
logger = logging.getLogger('Command')
logger.setLevel(logging.DEBUG)
logger.addHandler(logging.StreamHandler())
# decorator needs a logger object
@command_decorator(logger)
def f_example(a):
print("managing proces... with args: %s" %(a))
time.sleep(2)
return(3 * a)
f_example(2)
@ssoto
Copy link
Author

ssoto commented Jun 1, 2017

This Decorator is used to take measure of lapsed seconds spent executing a function and send output to a logging object.

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