由于缺乏准确性,我总是被一点点跟踪,因为我看到了台架标记system.time和rbenchmark(因为时间的精确度可能不足)并且看到Hadley microbenchmark最近参考了这个包.所以我决定给它一个旋转,如下所示.我mean反对f <- function(x) {sum(x)/length(x)}并期望mean做得更好,f但结果,正如我理解的那样,并不表明这是真的.
我在win 7机器上运行R2.15(因为microbenchmark根据你的操作系统做不同的时间).
结果
Unit: microseconds
expr min lq median uq max
1 f(x) 19.130 20.529 20.529 20.996 286.00
2 mean(x) 28.927 29.860 30.327 30.327 672.31
Run Code Online (Sandbox Code Playgroud)
代码
library(microbenchmark)
x <- 1:10000
f <- function(x) {sum(x)/length(x)}
mean(x)
res <- microbenchmark(
mean(x),
f(x),
times=1000L)
print(res)
boxplot(res)
Run Code Online (Sandbox Code Playgroud)
我可能是错的,但这似乎并不令我感到惊讶.之前mean.default可以调用.Internal(mean(x))它来检查3个if语句,计算长度x,然后检查另一个if语句.它的时间差异相当小.
.Internal(mean(x)直接呼叫仍然稍微快一些:
library(microbenchmark)
x <- 1:10000
f1 <- function(x) {sum(x)/length(x)}
f2 <- function(x) {.Internal(mean(x))}
res <- microbenchmark(
mean(x),
f1(x),
f2(x),
times=1000L)
print(res)
Unit: microseconds
expr min lq median uq max
1 f1(x) 32.195 32.4605 32.8850 33.4645 106.997
2 f2(x) 21.840 22.0580 22.2015 22.6270 55.316
3 mean(x) 35.393 35.9840 36.1860 36.4420 91.203
Run Code Online (Sandbox Code Playgroud)