R 并行化失败 - 多核处理减慢玩具示例 总结MRE - 最小可重复示例

问题描述

我刚开始学习一些关于 R 中并行化/多核处理的基本教程。 以下是我使用的两个教程:jottr.orgblasbenito.com

我还在学习。但是我认为我掌握了基本概念,例如什么构成了令人尴尬的并行任务。我从两个教程中复制了玩具示例。应该并行化的基本任务是为大小为 n 的向量中的每个条目获取平方根。

我惊讶地看到,所有四种并行方法所需的时间都是简单/第一种顺序方法所需的时间的倍数。我错过了什么重要的事情吗?我很难找出原因。

总结

  • 连续运行 1。:0.037 秒过去
  • 连续运行 2。:5.659 秒过去
  • 多核运行 1。:6.999 秒过去
  • 多核运行 2。:8.749 秒过去
  • 多核运行 3。:6.914 秒过去
  • 多核运行 4。:1.854 秒过去

MRE - 最小可重复示例

设置玩具示例

# Cleaning Up the Session
require(pacman)
p_unload()
rm(list=ls())

# Quick Loading of all required packages
#automatic install of packages if they are not installed already
list.of.packages <- c(
  "foreach","doParallel","ranger","palmerpenguins","tidyverse","kableExtra"
)
require(pacman)
p_load(list.of.packages,character.only=T)


# Testing Settings Max N 
n = 10000
X <- 1:n

顺序运行 1

tic()
y <- list()
for (ii in seq_along(X)) {
  y[[ii]] <- local({
    x <- X[[ii]]
    tmp <- sqrt(x)
    tmp            ## same as return(tmp)
  })
}
toc()

连续跑 2

tic()
z <- foreach(x = 1:n,.combine = 'c') %do% {
  sqrt(x)
}
toc()

多核运行 1 - 4 核

cl <- parallel::makeCluster(4)
doParallel::registerDoParallel(cl)
tic()
multi <- foreach(i = 1:n,.combine = 'c') %dopar% {
  sqrt(i)
}
toc()

多核运行 2 - 15 核集群

n.cores <- parallel::detectCores() - 1
n.cores
#create the cluster
my.cluster <- parallel::makeCluster(
  n.cores,type = "PSOCK"
)

#check cluster deFinition (optional)
print(my.cluster)

#register it to be used by %dopar%
doParallel::registerDoParallel(cl = my.cluster)

#check if it is registered (optional)
foreach::getDoParRegistered()
foreach::getDoParWorkers()
tic()
x <- foreach(
  i = 1:10000,.combine = 'c'
) %dopar% {
  sqrt(i)
}
# x
toc()
stopCluster(cl)

多核运行 3 - jottr.org doFuture

require(doFuture)
registerDoFuture()
plan(multiprocess)

tic()
y <- foreach(x = X) %dopar% {
  tmp <- sqrt(x)
  tmp
}
toc()

多核运行 4 - jottr.org future.apply

require(future.apply)
plan(multiprocess) ## => parallelize on your local computer

tic()
y <- future_lapply(X,function(x) {
  tmp <- sqrt(x)
  tmp
})
toc()

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)