Search code examples
pythonprofilingdecorator

A decorator that profiles a method call and logs the profiling result


I want to create a decorator that profiles a method and logs the result. How can this be done?


Solution

  • The decorator would look something like:

    import time
    import logging
    
    def profile(func):
        def wrap(*args, **kwargs):
            started_at = time.time()
            result = func(*args, **kwargs)
            logging.info(time.time() - started_at)
            return result
    
        return wrap
    
    @profile
    def foo():
        pass
    

    Anyway, if you want to do some serious profiling I would suggest you use the profile or cProfile packages.