为什么使用并行这两个函数的处理时间会有所不同?

时间:2019-06-27 15:10:39

标签: r parallel-processing

想象一下,我有两个函数,一个是平方和的简单均值,另一个是用于计算回归的更详细的函数,我想将其应用于“大”矩阵或数据框的行。

为了利用多个内核(在Windows上),我尝试了parallel软件包,并使用相同的命令序列获得了两个函数的不同结果。

对于看似更复杂的功能(回归),使用更多的内核似乎可以显着减少时间(此处显示了3核PC和12核PC的结果,行为相似,最多11核)核心,减少的时间会随着更多核心而减少)。 enter image description here enter image description here

但是对于“简单”函数(均方根),执行时间是非常可变的,几乎是不稳定的(也已通过多达11个内核进行了测试)。 enter image description here enter image description here

首先,发生这种情况是否有原因?其次,我想还有其他方法可以完成该任务,您能提出任何建议吗?

以下是生成绘图的代码:

library(parallel)
nc=detectCores()-1  #number of cores
myFun =function(z) coef(lm(rep(1,length(z))~z)) #regression
myFun2 =function(z) sum(z^2)/length(z) # mean  of squares
my.mat = matrix(rnorm(1000000,.01,0.4),ncol=100) #data
# using FUN = myFun 
# Replicate 10 times
for(j in 1:10){
ncor=2:nc
timed=c()
for (i in seq_along(ncor)){
cl <- makeCluster(mc <- getOption("cl.cores", ncor[i]))
stime <- Sys.time()
res=parApply(cl = cl, X = my.mat, MARGIN = 1, FUN = myFun)
tm=Sys.time()-stime
timed[i]=tm
stopCluster(cl)
}
# no cores
stime <- Sys.time()
res=apply(my.mat, MARGIN = 1, FUN = myFun)
tm=Sys.time()-stime
(dr=data.frame(nc=c(1,ncor),ts=as.numeric(c(tm,timed))))
plot(dr,type="l",col=3,main=j)
#stopCluster(cl)
if (j==1)fres1=dr else fres1=merge(fres1,dr,by="nc")
}
plot(fres1[,1:2],type="l",col=2,ylim=range(fres1[,-1]))
for(i in 3:11)lines(fres1[,i],col=i+1)

# For the second plot use the same code but change FUN = myFun2

0 个答案:

没有答案