jmquintana79
9/24/2017 - 9:30 AM

decorator time execution

Decorator to display information of time execution.

## OPTION 1 ##

## time execution decorator (no impact on help() function)
from functools import wraps
def time_dec(func):
    @wraps(func)
    def wrapper(*arg):
        from datetime import datetime, timedelta
        # current time
        tic = datetime.now()
        # function execution
        res = func(*arg)
        # calculate time of processing
        toc = datetime.now()
        tictoc = ((toc-tic).seconds)/60. # minutes
        print ('[Process Time Spend] -- function "%s()" spent %s minutes --'%(func.__name__,tictoc))
        # function return
        return res
    return wrapper


@time_dec
def myFunction(n):
  return None
  
  
## OPTION 2 ##

# from bash, use unix command to return time execution
$time -p python function.py


from functools import wraps
import time

def timeit(func):
    @wraps(func)
    def new_func(*args, **kwargs):
        start_time = time.time()
        result = func(*args, **kwargs)
        elapsed_time = time.time() - start_time
        print('[info] Function "{}()" finished in {:.2f} {}.'.format(
            func.__name__, elapsed_time if elapsed_time < 60 else elapsed_time / 60., "seconds" if elapsed_time < 60 else "minutes"))
        return result
    return new_func


@timeit
def foobar():
    return "hola mundo"
import time

def timer(func):
    def wrapper(*args, **kwargs):
        # start the timer
        start_time = time.time()
        # call the decorated function
        result = func(*args, **kwargs)
        # remeasure the time
        end_time = time.time()
        # compute the elapsed time and print it
        execution_time = end_time - start_time
        print(f"Execution time: {execution_time} seconds")
        # return the result of the decorated function execution
        return result
    # return reference to the wrapper function
    return wrapper