15

It is possible to record the time that was used to run some code using system.time. Here is a little example:

system.time(
  mean(rnorm(10^6))
  )

But I am not only interested in the time but also in the number of arithmetic operations (that is +,-,*,/) that were used for the code.

In the above-mentioned case it would be easy to count the number of summations and the division in order to get the mean, but the code I would like to apply this to is far more complex.

Therefore, my question is: is there a function in R that counts the number of arithmetic operations?

ehi
  • 409
  • 8
  • 23
  • 4
    At the R level or also at the compiled level (Fortran, C/C++)? – Roland May 02 '17 at 16:01
  • Thanks for your comment! Personally I'd prefer the R level as I am not familiar with Fortran and C. But perhaps it'll be nice for others if you could share your solution. – ehi May 02 '17 at 21:16

1 Answers1

25

You can trace the R functions of interest:

counter <- 0 

trace("+", at = 1, print = FALSE,
      tracer = quote(.GlobalEnv$counter <- .GlobalEnv$counter + 1))
#Tracing function "+" in package "base"
#[1] "+"

Reduce("+", 1:10)
#[1] 55

counter
#[1] 9

untrace("+")
#Untracing function "+" in package "base"

I'm not sure how useful it would be to count R level calls here. Many (most?) functions do arithmetic in C or Fortran code or even the BLAS. And I don't have a solution for counting calls in compiled code. You'd need to set that up during compilation if it is possible at all.

Roland
  • 127,288
  • 10
  • 191
  • 288
  • Thanks so much for your solution! Is it also possible to use this for example for a linear model? For example to count the arithmetic operations of `lm(mpg~disp, data = mtcars)`? – ehi May 03 '17 at 11:00
  • The last paragraph of my answer applies to `lm`. – Roland May 03 '17 at 11:29