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?
Arithmetic operations include addition (+), subtraction (-), multiplication(*), division (/) and modulus(%).
In R: %/% is the integral division operator. example: 5 %/% 3 will be equal to 1 as it is the quotient obtained on the integral division of 5 by 3.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With