Speed comparison of sapply with a composite function

寵の児 提交于 2019-12-06 05:20:55

问题


> 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 was trying this out after reading the answers to the R tips question. I did not expect sapply to be order of magnitude slower than the equivalent composite function in the above case. Does anyone know why this is the case? If i understand correctly sapply will vectorize and be near optimally fast.


回答1:


There's nothing here to sapply to - you only give it a single vector - not a list of vectors, and sapply converts the result to a (single column) matrix.

sapply is simplifying the result for you, but in doing so has to generate an array.

Compare if you give it 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:


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

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

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



来源:https://stackoverflow.com/questions/4600243/speed-comparison-of-sapply-with-a-composite-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!