Counting automatically the number of arithmetic operations of a function

Hello,

Say I have one function with hundreds of lines of code, with a few internal functions and perhaps with calls to some mathematical functions (sqrt, tan…). I’d like to know how many arithmetic operations (e.g. number of + and *) in this function.

Here is a simplified example of a function to be analyzed. How can it be analyzed automatically?

function f(a,b)
    g(x,y) = x+y # internal function to reuse some long expression
    c = g(a,b)
    d = g(c, tan(a)) # call to external mathematical function
    return d
end

Since I have little background in algorithmic complexity, I not sure my question even makes sense…

I suppose that the analysis should be done at the AST level. Or perhaps with a single run of the function-under-test with some custom input types which would perform operator overloading?

In the end, my goal is to be able to comment on the run time of the function. That is : "is a running time of x milliseconds consistent with the “amount of work” the CPU has to do.

Maybe this relates to Macro for counting the number of times a function is called? except I’m not interested in upper-level function calls (i.e. g or tan above), only the total number of low-level operations (i.e. g or tan included).

3 Likes

Check GitHub - triscale-innov/GFlops.jl: Estimate the absolute performance of a piece of Julia code

4 Likes

If your code is type-generic then you could pass in a special number type that increments a counter every time an operation is applied. Not sure how well that would work in general.

Thanks, GFlops sounds exactly what I’m trying to achieve. As written in the README, I indeed want to “objectivise what is “slow” or “fast””.