How do I parallelize in r on windows - example?

后端 未结 6 1217
滥情空心
滥情空心 2020-12-13 02:00

How do I get parallelizaton of code to work in r in Windows? Include a simple example. Posting this self-answered question because this was rather unpleasant to get working.

6条回答
  •  一整个雨季
    2020-12-13 03:00

    Posting this because this took me bloody forever to figure out. Here's a simple example of parallelization in r that will let you test if things are working right for you and get you on the right path.

    library(snow)
    z=vector('list',4)
    z=1:4
    system.time(lapply(z,function(x) Sys.sleep(1)))
    cl<-makeCluster(###YOUR NUMBER OF CORES GOES HERE ###,type="SOCK")
    system.time(clusterApply(cl, z,function(x) Sys.sleep(1)))
    stopCluster(cl)
    

    You should also use library doSNOW to register foreach to the snow cluster, this will cause many packages to parallelize automatically. The command to register is registerDoSNOW(cl) (with cl being the return value from makeCluster()) , the command that undoes registration is registerDoSEQ(). Don't forget to turn off your clusters.

提交回复
热议问题