Last active
October 11, 2017 14:45
-
-
Save ssoto/39a93011c29e06db6282da2b843eb06b to your computer and use it in GitHub Desktop.
Benchmark decorator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This Decorator is used to take measure of lapsed seconds spent executing a function and send output to a logging object.