我一直對缺乏準確性有些迷惑,我看到system.time
和rbenchmark
(因爲時間的精度可能不足),並看到Hadley最近參考了microbenchmark
包。所以我決定給它一個旋轉,如下所示。我將mean
與f <- function(x) {sum(x)/length(x)}
對齊,預計mean
比f
做得更好,但據我瞭解,結果並不表明這是真的。意想不到的結果:microbenchmark
- 我誤解了結果嗎?
- f實際上是否比平均速度更快?
- microbenchmark仍處於測試階段,這需要熨燙 了嗎?
我在贏得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
守則
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)
我喜歡'microbenchmark'。如果你做的不止一個或兩個結果,繪圖可以幫助很大,但是在醜陋的一面,默認輸出是一點點。我爲ggplot2寫了一個autoplot函數,可能會在其中一個版本中顯示(同時檢查github)。示例:http://stackoverflow.com/a/6919493/636656 – 2012-04-28 16:52:09
這可能解釋它http://radfordneal.wordpress.com/2014/02/02/inaccurate-results-from-microbenchmark/ – Momo 2014-02-02 23:31:56
可能不是所有的統計數據'f'較低,散點圖也表明了這一點。喬蘭釘了這一個。 – 2014-02-03 02:21:01