1 前言

以下示範如何將迴圈運算改成向量化運算,並且透過使用多個CPU核心平行運算,進一步縮短運算時間。

2 使用for迴圈

# 產生三組常態分佈的樣本
set.seed(7)
x.list <- list(a = rnorm(100000),
               b = rnorm(100000),
               c = rnorm(100000))


# 計算每組樣本的平均值與標準差
kN <- length(x.list)
lis01 <- list()

for (i in 1:kN){
  lis01[[i]] <- c(mean(x.list[[i]]), sd(x.list[[i]]))
  }

3 使用lapply

lis02 <- lapply(x.list, function(x) c(mean(x), sd(x)))

4 使用parLapply平行運算

# 載入套件
library(parallel)

# 取得CPU核心數
cpu.cores <- detectCores()

# 建立平行運算叢集
cl <- makeCluster(2)

# 叢集載入指定套件
clusterEvalQ(cl, library(e1071))

# 變數y傳進叢集
y <- 3
clusterExport(cl, "y")

# 平行計算
lis03 <-parLapply(cl, x.list,
                  function(x) c(mean(x), sd(x)))

exp <- parLapply(cl, c(1, 2, 3),
                 function(x) x^y)
  # 若沒有事先將y傳進叢集,parLapply會找不到y

# 關閉平行運算
stopCluster(cl)

5 檢查輸出結果

# 確認三種方法的結果一致
lis01
## [[1]]
## [1] 0.1039757 1.2666634
## 
## [[2]]
## [1] 0.7825171 1.1727688
## 
## [[3]]
## [1] 0.3005079 0.9155842

lis02
## $a
## [1] 0.1039757 1.2666634
## 
## $b
## [1] 0.7825171 1.1727688
## 
## $c
## [1] 0.3005079 0.9155842

lis03
## $a
## [1] 0.1039757 1.2666634
## 
## $b
## [1] 0.7825171 1.1727688
## 
## $c
## [1] 0.3005079 0.9155842