2013-03-07 48 views
8

我要評估的不同版本R的一些代碼的性能這在原則上很容易:如何使用knitr來比較不同版本R的性能?

  • 開始[R
  • 使用system.time()來衡量它需要運行一段代碼
  • 時間
  • 終止[R
  • 沖洗,並在不同的版本

現在,我想用knitr創建報告要做到這一點重複。所以,在我看來,我需要一種機制在每個塊中開始新的會話。

我該怎麼做?


一些樣品knitr降價代碼作爲示範。此代碼使用ggplot繪製圖形,但顯然兩個版本都返回相同的計時,因爲我不知道如何爲每個塊啓動新版本的R。

Comparison of R performance 
======================================================== 

# Do analysis in R version 2.14 

```{r fig.width=6, fig.height=3} 
library(ggplot2) 
data(diamonds) 

system.time({ 
    p <- ggplot(diamonds, aes(carat, price/carat, colour=clarity)) + geom_point() 
    print(p) 
}) 
``` 


# Repeat same analysis in R 2.15 

```{r fig.width=6, fig.height=3} 
library(ggplot2) 
data(diamonds) 

system.time({ 
    p <- ggplot(diamonds, aes(carat, price/carat, colour=clarity)) + geom_point() 
    print(p) 
}) 
``` 
+2

難道你不可能只是有一個'bash'腳本或者不能完成R會話的所有開始/停止,每個會話都會將其結果寫入文件,然後使用'knitr'來讀取所有日誌文件並總結結果?不夠優雅,但可能更準確,更容易。 – 2013-03-07 12:40:20

+1

@ AriB.Friedman是的,可能。但這聽起來像工作! – Andrie 2013-03-07 12:47:50

+0

估計你需要使用'system()'來運行另一個R進程... – Spacedman 2013-03-07 15:17:58

回答

6

添加Rscript發動機knitrwas easy,但我被an R bug忍住。無論如何,這款引擎自version 1.1.5起可用,並且將作爲版本1.2在CRAN上。

現在,您可以指定塊選項engine='Rscript'engine.path='path/to/the/desired/Rscript'

對於大型的性能比較,我覺得阿里B.弗裏德曼建議在上面的註釋是一個更好的方式去。如果您有許多代碼塊進行比較,那麼鍵入引擎路徑將非常繁瑣。

+0

太棒了,謝謝! – Andrie 2013-03-10 16:03:29