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?
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.