計時 - 預先配置
在前一個練習中,逐步擴增向量大約花了 2 秒。
如果先預先配置向量,會花多少時間?下方已定義 pre_allocate() 函式。
n <- 30000
# Fast code
pre_allocate <- function(n) {
x <- numeric(n) # Pre-allocate
for(i in 1:n)
x[i] <- rnorm(1)
x
}
本練習屬於課程
撰寫高效 R 程式碼
練習說明
pre_allocate() 函式已在你的工作空間中可用。
- 使用
system.time()找出執行pre_allocate(n)所需的時間。用<-小技巧把結果儲存到物件res_allocate中。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Use <- with system.time() to store the result as res_allocate
n <- 30000
system.time(___ <- ___)