Ohumeronen
Ohumeronen

Reputation: 2086

Profile selected functions in Python

I can profile and visualize my entire application with:

python -m cProfile -o program.prof my_program.py
snakeviz program.prof

Is it possible to write a decorator that will profile only some functions?

In the end this would look like this:

# This is the profiling decorator function.
def profile_function(func):
    def wrapper(*args, **kwargs):
        
        # TODO write profiling information to program.prof
        
        return func(*args, **kwargs)
    return wrapper


@profile_function
def function1():
    for _ in range(0, 1000):
        _**2


@profile_function
def function2():
    for _ in range(0, 100000):
        _**4


# Do not profile function3
def function3():
    return


function1()
function2()
function3()

Upvotes: 0

Views: 38

Answers (0)

Related Questions