# Determine the number of times a function will be called

I have a function func[x], which is rather slow to evaluate. It gets called (multiple times) inside other expressions; I'd like to know how many times it gets called (without actually evaluating the expression). (This is so I can estimate how long it will take.) For example, I'd like to make a function that would take 3x*Hold[func[4]]+Hold[func[5]]*Hold[func[6]] and return 3, because func would get called three times if I ran the code (with ReleaseHold).

I was thinking that string matching would be the way to go, namely come up with a list of symbols in 3x*Hold[func[4]]+Hold[func[5]]*Hold[func[6]], convert that into a list of strings, and then count the number of times func appears, but I haven't figured out a way to do the first two steps.

To be clear, I know that I'm always calling my function in expressions like the above, in which it's going to be evaluated once, so I only need to count the number of times "func" appears.

Help/ideas would be appreciated.

Have you looked at Count?

expr = HoldForm[3 x*func[4] + func[5]*func[6]]
Count[expr, func, ∞, Heads -> True]


3

• Thanks! Yes, I had tried count, but I was missing the "Heads->True", which makes it work. Could you explain what that does? – Lauren Pearce Oct 17 '16 at 1:11
• @LaurenPearce. Rather than me write an explanation that would just quote the docs, I suggest you look at this documentation article on the Heads option. Bear in mind that you are using func as a head in your expression. – m_goldberg Oct 18 '16 at 13:34

Maybe this?

Block[{n = 0, func = ++n &},
expr;
n]

Block[{n = 0, func = ++n &},
3 x*func[4] + func[5]*func[6];
n]
(*  3  *)


It's not really clear how the OP's expression is to be constructed or evaluated. Nor is it clear if func[] has side-effects or whether execution depends on the values it returns.