Comparison of nozzle speed with composite function

> system.time(sapply(rnorm(1000000,0,1), function (x) round(x,2))) user system elapsed 2.78 0.11 2.89 > system.time(round(rnorm(1000000,0,1),2)) user system elapsed 0.29 0.00 0.30 

I tried this by reading the answers to the R tips question. I did not expect sapply to be an order of magnitude slower than the equivalent composite function in the above case. Does anyone know why this is so? If I understand correctly, that sapply will vectorize and be almost optimally fast.

+4
source share
2 answers

There is nothing that could be used - you only pass it one vector - not a list of vectors, but simply convert the result into a matrix (one column).

sapply simplifies the result for you, but it should generate an array.

Compare if you give him a list:

 system.time(sapply(list(rnorm(1000000,0,1)), function (x) round(x,2))) user system elapsed 0.22 0.00 0.22 system.time(sapply(rnorm(1000000,0,1), function (x) round(x,2))) user system elapsed 4.21 0.00 4.21 
+2
source

probably sapply, which is a simple lapply shell, is not vectorized. try this code:

 system.time(sapply(rnorm(10), function (x) {print(length(x)); round(x,2)})) 

and look at the implementation here: https://svn.r-project.org/R/trunk/src/main/apply.c

+5
source

Source: https://habr.com/ru/post/1334295/


All Articles