sapply 与复合函数的速度比较 [英] Speed comparison of sapply with a composite function

查看:53
本文介绍了sapply 与复合函数的速度比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

> 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 

我在阅读了 R 提示问题的答案后尝试了这一点.我没想到 sapply 比上述情况下的等效复合函数慢几个数量级.有谁知道为什么会这样?如果我理解正确 sapply 将矢量化并接近最佳速度.

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.

推荐答案

这里没有什么可应用的 - 你只给它一个向量 - 不是向量列表,并且 sapply 将结果转换为(单列)矩阵.

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 正在为您简化结果,但这样做必须生成一个数组.

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 

这篇关于sapply 与复合函数的速度比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆