为什么使用 %do% 循环使用多个处理器?预期的顺序循环

Why is using %do% loop is using multiple processors? Expected sequential loop

我正在使用 foreach 并阅读它,例如

我的理解是,您将使用 %dopar% 进行并行处理,使用 %do% 进行顺序处理。

碰巧我遇到了 %dopar% 的问题,在尝试调试时我将其更改为我认为是使用 %do% 的顺序循环。我碰巧打开了终端并注意到所有处理器 运行 而我 运行 循环。

这是预期的吗?

可重现的例子:

library(tidyverse)
library(caret)
library(foreach)

# expected to see parallel here because caret and xgb with train()
xgbFit <- train(Species ~ ., data = iris, method = "xgbTree", 
                trControl = trainControl(method = "cv", classProbs = TRUE))

iris_big <- do.call(rbind, replicate(1000, iris, simplify = F))

nr <- nrow(iris_big)
n <- 1000 # loop over in chunks of 20
pieces <- split(iris_big, rep(1:ceiling(nr/n), each=n, length.out=nr))
lenp <- length(pieces)

# did not expect to see parallel processing take place when running the block below
predictions <- foreach(i = seq_len(lenp)) %do% {

  # get prediction
  preds <- pieces[[i]] %>% 
    mutate(xgb_prediction = predict(xgbFit, newdata = .))

  return(preds)
}

bah <- do.call(rbind, predictions)

我最好的猜测是这些进程仍然是 运行 来自以前的运行。

使用foreach::registerDoSeq()也是一样吗?

我的第二个猜测是 predict 并行运行。