并行加载文件不能与foreach + data.table一起使用

时间:2013-02-01 16:24:20

标签: r foreach parallel-processing data.table

我想将foreachdata.table(v.1.8.7)结合使用来加载文件并绑定它们。 foreach没有并行化,并返回警告......

write.table(matrix(rnorm(5e6),nrow=5e5),"myFile.csv",quote=F,sep=",",row.names=F,col.names=T) 
library(data.table); 
#I use fread from data.table 1.8.7 (dev) for performance and useability
DT = fread("myFile.csv") 

现在假设我有n个要加载和rowbind的文件,我想把它搞定。 (我在Windows上,所以没有分叉)

allFiles = rep("myFile.csv",4) # you can change 3 to whatever

使用lapply

f1 <- function(allFiles){
    DT <- lapply(allFiles, FUN=fread) #will load sequentially myFile.csv 3 times with fread
    DT <- rbindlist(DT);
    return(DT);
}

single thread

使用parallel(R的一部分为2.14.0)

library(parallel)
f2 <- function(allFiles){
    mc <- detectCores(); #how many cores?
    cl <- makeCluster(mc); #build the cluster
    DT <- parLapply(cl,allFiles,fun=fread); #call fread on each core (well... using each core at least)
    stopCluster(cl);
    DT <- rbindlist(DT);
    return(DT);
}

here it uses both proc

现在我想使用foreach

library(foreach)
f3 <- function(allFiles){
    DT <- foreach(myFile=allFiles, .combine='rbind', .inorder=FALSE) %dopar% fread(myFile)
    return(DT);
}

enter image description here


以下是一些基准确认我无法解决foreach工作

system.time(DT <- f1(allFiles));
utilisateur     systÞme      ÚcoulÚ
      34.61        0.14       34.84
system.time(DT <- f2(allFiles));
utilisateur     systÞme      ÚcoulÚ
       1.03        0.40       24.30    
system.time(DT <- f3(allFiles));
executing %dopar% sequentially: no parallel backend registered
utilisateur     systÞme      ÚcoulÚ
      35.05        0.22       35.38

1 个答案:

答案 0 :(得分:2)

只是为了得到答案:

正如警告消息所示,没有为foreach注册的并行后端。阅读this vignette以了解如何执行此操作。

小插图的简单例子:

library(doParallel) 
cl <- makeCluster(3) 
registerDoParallel(cl) 
foreach(i=1:3) %dopar% sqrt(i) 
相关问题