通常R語言運行都是在CPU單個核上的單線程程序。有時我們會有需求對一個向量里的元素應用相同的函數,最終再將結果合並,並行計算可以大幅節約時間。
為了支持R的並行運算, parallel包已經被納入了R的BASE庫中,可以被直接調用,來實現在同一個CPU上利用多個核Core同時運算相同的函數。
版本一、Window版本的R程序
對比普通的LAPPLY函數和Parallel包下的多核makeCluster + parLapply函數效率
library(parallel)
fun <- function(x){
return (x+1);
}
funcTwoPara<
-function
(x,a){
return (x+a);
}
#單核的普通LAPPLY函數
system.time({
res <- lapply(1:5000000, fun);
});
# 用戶 系統 流逝
# 20.91 0.03 21.35
# 超過一個參數的 Function模型
x=c(1:500)
system.time({
res <- lapply(x,funcTwoPara,a=1);
});
#多核的 MakeCluster 函數,這里利用了本機CPU的2個物理核心同時跑程序
detectCores()
# 4 core
detectCores(logical = F)
# 2 core 物理核心
cl <- makeCluster(getOption(
"cl.cores"
, 4));
system.time({
res <- parLapply(cl, 1:10000000, fun)
});
stopCluster(cl);
|
版本二、Linux版本的R程序
library(parallel)
fun <- function(x){
return (x+1);
}
# 單核計算
system.time({
res <- lapply(1:5000000, fun);
});
# 多核並行計算
detectCores(logical = F)
# 8
mc <- getOption(
"mc.cores"
, 8)
system.time({
res <- mclapply(1:5000000, fun, mc.cores = mc);
});
stopCluster(mc);
# 8核的 結果
user system elapsed
7.175 1.187 3.416
# 4核的結果
user system elapsed
13.415 1.443 8.946
# 2核的結果
user system elapsed
16.882 1.726 8.139
# 單核 計算 結果
user system elapsed
16.760 0.039 16.807
|
Reference: