Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

The number of times a function gets called

Tags:

python

Let's say I want to integrate x**2 from 0 to 1. I do it using the scipy.integrate.quad:

from scipy import integrate
def f(x): return x**2
I = integrate.quad(f, 0, 1)[0]
print(I)

Questions: Is there any way to know how many times the user-defined function f gets called by the quad? I want to do it as I am interested to know how many have been utilized by quad to evaluate the integral.

like image 231
rainman Avatar asked Sep 21 '18 17:09

rainman


2 Answers

Sure. Use a call-counting wrapper:

import functools
def counted_calls(f):
    @functools.wraps(f)
    def count_wrapper(*args, **kwargs):
        count_wrapper.count += 1
        return f(*args, **kwargs)
    count_wrapper.count = 0
    return count_wrapper

And pass the wrapped version to quad:

wrapped = counted_calls(f)
integrate.quad(wrapped, 0, 1)
print(wrapped.count)

Demo, with a call count of 21.

I've specifically avoided using a global counter or using counted_calls as a decorator on the f definition (though you can use it as a decorator if you want), to make it easier to take separate counts. With a global, or using it as a decorator, you'd have to remember to manually reset the counter every time.

like image 79
user2357112 supports Monica Avatar answered Nov 04 '22 16:11

user2357112 supports Monica


Just add to a global whenever f is called:

from scipy import integrate
count = 0
def f(x):
    global count
    count += 1
    return x ** 2
I = integrate.quad(f, 0, 1)[0]
print(I)
print('called', count, 'times')
like image 32
Joe Iddon Avatar answered Nov 04 '22 14:11

Joe Iddon