【发布时间】:2011-05-11 08:19:22
【问题描述】:
我在 R 中工作时注意到一件奇怪的事情。 当我有一个使用 for-loop 和 while-loop 实现计算从 1 到 N 的平方的简单程序时,行为是不一样的。 (在这种情况下,我不关心矢量化或应用函数)。
fn1 <- function (N)
{
for(i in 1:N) {
y <- i*i
}
}
与
fn2 <- function (N)
{
i=1
while(i <= N) {
y <- i*i
i <- i + 1
}
}
结果是:
system.time(fn1(60000))
user system elapsed
2.500 0.012 2.493
There were 50 or more warnings (use warnings() to see the first 50)
Warning messages:
1: In i * i : NAs produced by integer overflow
.
.
.
system.time(fn2(60000))
user system elapsed
0.138 0.000 0.137
现在我们知道 for-loop 更快,我猜是因为那里的预分配和优化。但是为什么会溢出呢?
更新:所以现在尝试使用向量的另一种方式:
fn3 <- function (N)
{
i <- 1:N
y <- i*i
}
system.time(fn3(60000))
user system elapsed
0.008 0.000 0.009
Warning message:
In i * i : NAs produced by integer overflow
所以也许这是一个时髦的内存问题?我在具有 4Gb 内存和 R 中所有默认设置的 OS X 上运行。这发生在 32 位和 64 位版本中(除了时间更快)。
亚历克斯
【问题讨论】:
-
根据你的时间,while循环更快。
-
当你将 for 循环中的计数器转换为浮点数时,它会比 while 循环更快,但这只是因为 for 循环没有警告。
-
R 充满了这种废话。
-
好问题,不过。我喜欢性能分析。
标签: r for-loop floating-point while-loop