代码改变世界

R语言的并行运算(CPU多核)

2017-05-24 11:06  xplorerthik  阅读(18662)  评论(0编辑  收藏  举报

通常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:

http://blog.sina.com.cn/s/blog_6f194ed30101blpu.html

http://blog.itpub.net/24229571/viewspace-1120592/