Recherche de tag: decorator


Python cProfile as a decorator [Python]

12.07.2018     Plopp      python cprofile profiling profiler decorator 

  Quickly profile your functions with cProfile by using it as a decorator
import cProfile

def profileit(func):
    def profiled_func(*args, **kwargs):
        profile = cProfile.Profile()
        print("Profiling " + "\033[95m" + func.__name__ + "\033[0m") # colors
        try:
            profile.enable()
            result = func(*args, **kwargs)
            profile.disable()
            return result
        finally:
            profile.print_stats(sort="time")
    return profiled_func



##########
# Example #
##########

@profileit
def times2():
   for i in range(500000):
       j = i * 2
       j = add_one(j)

def add_one(n):
    return n+1

times2()
5/5 - [1 rating]