YYY*_*YYY 5 debugging parallel-processing r
我发现如果并行计算期间有多个打印函数,则只有最后一个会显示在控制台上。所以我设置了outfile选项,希望我能得到每次打印的结果。这是 R 代码:
cl <- makeCluster(3, type = "SOCK",outfile="log.txt")
abc <<- 123
clusterExport(cl,"abc")
clusterApplyLB(cl, 1:6,
function(y){
print(paste("before:",abc));
abc<<-y;
print(paste("after:",abc));
}
)
stopCluster(cl)
Run Code Online (Sandbox Code Playgroud)
但我只得到三个记录:
starting worker for localhost:11888
Type: EXEC
Type: EXEC
[1] "index: 3"
[1] "before: 123"
[1] "after: 2"
Type: EXEC
[1] "index: 6"
[1] "before: 2"
[1] "after: 6"
Type: DONE
Run Code Online (Sandbox Code Playgroud)
看起来您只获得了 log.txt 中一名工作人员的输出。我经常想知道这是否会发生,因为当您指定 时outfile="log.txt",每个工作人员都会打开 log.txt 进行追加,然后调用sink。outfile以下是当不是空字符串时工作进程执行的代码:
## all the workers log to the same file.
outcon <- file(outfile, open = "a")
sink(outcon)
sink(outcon, type = "message")
Run Code Online (Sandbox Code Playgroud)
这让我感到紧张,因为我不确定所有工作人员同时打开同一个文件进行附加会发生什么。它可能依赖于操作系统或文件系统,并且它可能解释为什么您只能从一名工作人员获得输出。
因此,我倾向于使用outfile="",在这种情况下,不会执行此代码,从而允许输出操作正常发生,而无需使用函数重定向它们sink。但是,在 Windows 上,如果使用 Rgui,则不会看到输出,因此请使用 Rterm。
任务中的多个 print 语句不应该有问题,但如果您没有设置outfile,您不应该看到任何输出,因为在这种情况下所有输出都被重定向到 /dev/null 。