diff --git a/client/ayon_core/lib/profiling.py b/client/ayon_core/lib/profiling.py index f3a31462006..e6d8714b3db 100644 --- a/client/ayon_core/lib/profiling.py +++ b/client/ayon_core/lib/profiling.py @@ -2,9 +2,10 @@ """Provide profiling decorator.""" import os import cProfile +import functools -def do_profile(fn, to_file=None): +def do_profile(to_file=None): """Wraps function in profiler run and print stat after it is done. Args: @@ -12,18 +13,30 @@ def do_profile(fn, to_file=None): instead of printing. """ + + def _do_profile(fn): + @functools.wraps(fn) + def profiled(*args, **kwargs): + profiler = cProfile.Profile() + try: + profiler.enable() + res = fn(*args, **kwargs) + profiler.disable() + return res + finally: + if to_file: + profiler.dump_stats(to_file) + else: + profiler.print_stats() + return profiled + + # If used as @do_profile, to_file is the function + if callable(to_file): + fn = to_file + to_file = None + return _do_profile(fn) + if to_file: to_file = to_file.format(pid=os.getpid()) - def profiled(*args, **kwargs): - profiler = cProfile.Profile() - try: - profiler.enable() - res = fn(*args, **kwargs) - profiler.disable() - return res - finally: - if to_file: - profiler.dump_stats(to_file) - else: - profiler.print_stats() + return _do_profile