Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to count the number of arithmetic operations in R?

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?

like image 575
ehi Avatar asked May 02 '17 15:05

ehi


People also ask

What are the arithmetic operations are applied on the matrix in R?

Arithmetic operations include addition (+), subtraction (-), multiplication(*), division (/) and modulus(%).

What does %/% do in R?

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.


1 Answers

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.

like image 168
Roland Avatar answered Sep 19 '22 12:09

Roland