参考:https://blog.csdn.net/weixin_41929524/article/details/81742322

    根据作者的表述,parallel 包存在不稳定的问题。

    另外,其创建的核心并行环境与主环境隔离,调用变量也并不方便。

    snowfall 闪亮登场了,其思路和parallel 一样,使用起来都是分为三个主要步骤:初始化并行、操作并行、结束并行并返还内存。

    1. > sfInit(parallel = TRUE, cpus = detectCores() - 1)
    2. R Version: R version 3.6.3 (2020-02-29)
    3. snowfall 1.84-6.1 initialized (using snow 0.4-3): parallel execution on 3 CPUs.
    4. # 初始化
    5. a<- matrix(1:10, ncol = 2)
    6. sfApply(a, 1, max)
    7. # 结束,返还内存
    8. sfStop()

    外部对象与变量:

    1. sfLibrary(MASS) # 载入依赖R包MASS
    2. sfLibrary(ggplot2) # 载入依赖R包ggplot2
    3. sfExport("n", "m") # 载入依赖的对象
    4. sfExport("fun1", "fun2") # 载入依赖的函数

    不同于parallel,我们可以将所有并行语句中需要使用的对象和函数放在一个文件中,接着source 它一下,就可以加载了:

    1. > sfSource('test.R')
    2. Calling a snowfall function without calling 'sfInit' first or after sfStop().
    3. 'sfInit()' is called now.
    4. snowfall 1.84-6.1 initialized: sequential execution, one CPU.
    5. > x <- 3

    使用sfCat查看并行进度

    这部分参考:https://stackoverflow.com/questions/8860470/how-to-output-a-message-in-snowfall

    我们只需在函数中添加sfCat()函数,即可查看并行进度,其示例代码如下所示:

    1. sfInit(parallel = TRUE, cpus = 2, slaveOutfile = "test.txt")
    2. sfLibrary(snowfall)
    3. res <- sfLapply(1:100, function(x) {
    4. sfCat(paste("Iteration ", x), sep = "\n")
    5. })
    6. sfStop()

    需要注意的是,在初始化并行中,我们多加了一串命令:slaveOutfile = “test.txt”,这个表示其显示的进度会储存在test.txt文件中,其余部分基本没什么变化。