使用 parSapply()
先前我們玩過下面這個遊戲:
- 初始化:
total = 0。 - 擲一顆骰子,並將點數加到
total。 - 如果
total為偶數,將total重設為 0。 - 如果
total大於 10,遊戲結束。
這個遊戲可以用 play() 函式來模擬:
play <- function() {
total <- no_of_rolls <- 0
while(total < 10) {
total <- total + sample(1:6, 1)
# If even. Reset to 0
if(total %% 2 == 0) total <- 0
no_of_rolls <- no_of_rolls + 1
}
no_of_rolls
}
要將遊戲模擬 100 次,我們可以使用 for 迴圈或 sapply():
res <- sapply(1:100, function(i) play())
這非常適合用平行運算來執行!
若要在叢集上使用函式,你可以呼叫 clusterExport()。這個函式需要叢集物件,以及一個為函式命名的字串。
clusterExport(cl, "some_function")
本練習屬於課程
撰寫高效 R 程式碼
練習說明
play() 函式已經定義在你的工作空間中。
- 使用
makeCluster()建立一個叢集;將核心數設為 2。把結果存為cl。 - 將
play()函式匯出到叢集。 - 將上面的
sapply()函式改寫為parSapply()。 - 使用
stopCluster()停止叢集。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
library("parallel")
# Create a cluster via makeCluster (2 cores)
cl <- ___
# Export the play() function to the cluster
___
# Re-write sapply as parSapply
res <- sapply(1:100, function(i) play())
# Stop the cluster
___