Python cProfiler Decorator [With Example]

A cProfile decorator is a Python programming concept that involves using the cProfile module to profile the performance of a Python function or method.

Profiling helps you understand how much time your code spends on various operations, which can be useful for identifying bottlenecks and optimizing your code.

cProfile Decorator Example

Here’s an example of how you can create a cProfile decorator:

import cProfile

def profiled(func):
    def wrapper(*args, **kwargs):
        profiler = cProfile.Profile()
        profiler.enable()
        result = func(*args, **kwargs)
        profiler.disable()
        profiler.print_stats(sort='cumulative')
        return result
    return wrapper

@profiled
def some_function():
    # Your code here
    pass

some_function()Code language: Python (python)

In this example:

  1. We import the cProfile module.
  2. We define a profiled decorator function that takes another function (func) as its argument.
  3. Inside the wrapper function, we create a cProfile.Profile() object to start profiling.
  4. We enable profiling with profiler.enable().
  5. We call the original function func with the provided arguments and keyword arguments and store its result in the result variable.
  6. We disable profiling with profiler.disable().
  7. We print the profiling statistics using profiler.print_stats(sort='cumulative'). This line prints the cumulative statistics, which can help you identify which functions or parts of your code consume the most time.
  8. Finally, the wrapper function returns the result of the original function.

To use this cProfile decorator, you simply decorate the functions or methods you want to profile with @profiled. When you call the decorated function, it will be profiled, and the profiling statistics will be printed.

Keep in mind that profiling adds some overhead to your code, so you should use it for performance analysis and optimization purposes, and not in production code.

Read More;

  • Abdullah Walied Allama is a driven programmer who earned his Bachelor's degree in Computer Science from Alexandria University's Faculty of Computer and Data Science. He is passionate about constructing problem-solving models and excels in various technical skills, including Python, data science, data analysis, Java, SQL, HTML, CSS, and JavaScript.

    View all posts

Leave a Comment