How to Track the Number of Times a Function Is Called

C++: Keep track of times function is called

Have a static variable in your function and keep incrementing it each time the function in called.

void my_Function(void) {
static unsigned int call_count = 0;
call_count++;
}

If you want to do it for debugging reasons, then there are tools like gcov which do this for you. (I'm pretty sure Microsoft doesn't have an alternative bundled with Microsoft Visual C++)

How do I find out how many times a function is called with javascript/jquery?

You could simply use a global variable, which is increased each time you call the function:

var myFuncCalls = 0;

function myFunction()
{
myFuncCalls++;
alert( "I have been called " + myFuncCalls + " times" );
}

As soon as your code gets a little more complex (or if you use a lot of other libraries), you should, however, consider using scoping as shown in the other answers here (best explained in the one by Vilx).

Javascript Function that Counts How Many Times the Function was Called

You could attach a property to the function itself that keeps track of the count:

const countTimesCalled = () => {
if (!countTimesCalled.count) {
countTimesCalled.count = 0;
}

return ++countTimesCalled.count;
};

console.log(countTimesCalled());
console.log(countTimesCalled());
console.log(countTimesCalled());

Counting how many times a function is called recursively (Python)

Why not add a second parameter to your function and increment that on recursive calls?

def fn(n):
def _fn(n, calls):
if n <= 1:
return n, calls
# n > 1 is a given by this point.
return _fn(n / 2 if n % 2 == 0 else 3 * n + 1, calls + 1)

return _fn(n, 1)


Related Topics



Leave a reply



Submit