R parallel包实现多线程1

并行执行

Yes! Well done! Socket clusters are initialized without variables, so a_global_var wasn't found. Fork clusters take a copy of global variables, but changes made after the cluster is created are not copied to each node.

parallel包

> # A global variable and is defined
> a_global_var <- "before"
> 
> # Create a fork cluster with 2 nodes
> cl_fork <- makeCluster(2, type = "FORK")
> 
> # Change the global var to "after"
> a_global_var <- "after"
> 
> # Evaluate the print fun on each node again
> clusterCall(cl_fork ,print_global_var)
[[1]]
[1] "before"

[[2]]
[1] "before"
> 
> # Stop the cluster
> stopCluster(cl_fork)
> 

总的来说,R的运算速度不算快,不过类似并行运算之类的改进可以提高运算的性能。下面非常简要地介绍如何利用R语言进行并行运算


        library(parallel)

        cl.cores <- detectCores()

        cl <- makeCluster(cl.cores) 创建并行云算的个数

        detectCores( )检查当前电脑可用核数。
    makeCluster(cl.cores)使用刚才检测的核并行运算。R-Doc里这样描述makeCluster函数:Creates a set of copies of R running in parallel and communicating over sockets. 即同时创建数个R进行并行运算。在该函数执行后就已经开始并行运算了,电脑可能会变卡一点。尤其在执行par开头的函数时。



   在并行运算环境下,常用的一些计算方法如下:

  ####1. clusterEvalQ(cl,expr)函数利用创建的cl执行expr

      这里利用刚才创建的cl核并行运算expr。expr是执行命令的语句,不过如果命令太长的话,一般写到文件里比较好。比如把想执行的命令放在Rcode.r里:

      clusterEvalQ(cl,source(file="Rcode.r"))

#### 2.par开头的apply函数族。

    这族函数和apply的用法基本一样,不过要多加一个参数cl。一般如果cl创建如上面cl <- makeCluster(cl.cores)的话,这个参数可以直接用作parApply(cl=cl,…)。当然Apply也可以是Sapply,Lapply等等。注意par后面的第一个字母是要大写的,而一般的apply函数族第一个字母不大写。另外要注意,即使构建了并行运算的核,不使用parApply()函数,而使用apply()函数的话,则仍然没有实现并行运算。换句话说,makeCluster只是创建了待用的核,而不是并行运算的环境。

  最后,终止并行运算只需要一行命令
           stopCluster(cl)

demo1 不使用并行计算,单纯的使用lapply函数

fun <- function(x){
return (x+1);
}
 
system.time({
res <- lapply(1:5000000, fun);
});
 
user  system elapsed
21.42    1.74   25.70

demo2 使用parallel进行并行计算

library(parallel)
#打开四核,具体核数根据机器的核数决定
cl <- makeCluster(getOption("cl.cores", 4));
system.time({
res <- parLapply(cl, 1:5000000,  fun)
});
user system elapsed
6.54 0.34 19.95
#关闭并行计算
stopCluster(cl);

比较两个的结果,可以很明显的看出并行计算的效率更高

library(parallel);#加载并行计算包

cl <- makeCluster(8);# 初始化cpu集群

clusterEvalQ(cl,library(RODBC));#添加并行计算中用到的包

clusterExport(cl,'variablename');#添加并行计算中用到的环境变量(如当前上下文中定义的方法)

dt <- parApply(cl,stasList, 1, stasPowerPre_Time);# apply的并行版本

all_predata_time <- do.call('rbind',dt);# 整合结果

猜你喜欢

转载自www.cnblogs.com/gaowenxingxing/p/12021817.html
今日推荐