2017-07-01 52 views
1

我R中作了如下顺序迷你例如:R:并行与doParallel和foreach

all_list <- list() 
all_list[1] <- list(1:6000) 
all_list[2] <- list(100000:450000) 
all_list[3] <- list(600000:1700000) 
all_list[4] <- list(2000000:3300000) 
all_list[5] <- list(3600000:5000000) 

find <- list(c(12800, 12800, 12800, 25600, 51200, 102400, 204800, 409600, 819200, 1638400, 1638400, 2457600, 3276800, 4096000, 4915200, 4915200)) 
result <- list() 
index <- 1 
current_Intervall <- 1 
current_number <- 1 

while(current_number <= 5000000){ 

    for(i in 1:length(find[[1]])){ 
    if(current_number == find[[1]][i]){ 
     result[[index]] <- current_number 
     index <- index + 1 
     break 
    } 
    } 

    current_number <- current_number + 1 
    last <- lengths(all_list[current_Intervall]) 
    if(current_number > all_list[[current_Intervall]][last]){ 
    if(current_Intervall == length(all_list)){ 
     break 
    }else{ 
     current_Intervall <- current_Intervall + 1 
     current_number <- all_list[[current_Intervall]][1] 
    } 
    } 
    print(current_number) 
} 

我想使这个代码的并行适用于Windows。我想到了doParallel包和foreach循环,因为我没有找到一个包,它支持parallel while循环。现在我试过了:

library(doParallel) 


all_list <- list() 
all_list[1] <- list(1:6000) 
all_list[2] <- list(100000:450000) 
all_list[3] <- list(600000:1700000) 
all_list[4] <- list(2000000:3300000) 
all_list[5] <- list(3600000:5000000) 

find <- list(c(12800, 12800, 12800, 25600, 51200, 102400, 204800, 409600, 819200, 1638400, 1638400, 2457600, 3276800, 4096000, 4915200, 4915200)) 
result <- list() 
index <- 1 
current_Intervall <- 1 
current_number <- 1 


no_cores <- detectCores() - 1 
cl <- makeCluster(no_cores) 
registerDoParallel(cl) 

print(current_number) 

foreach(current_number=1:5000000) %dopar% { 
    for(i in 1:length(find[[1]])){ 
    if(current_number == find[[1]][i]){ 
     result[[index]] <- current_number 
     index <- index + 1 
     break 
    } 
    } 

    # current_number <- current_number + 1 
    last <- lengths(all_list[current_Intervall]) 
    if(current_number > all_list[[current_Intervall]][last]){ 
    if(current_Intervall == length(all_list)){ 
     break 
    }else{ 
     current_Intervall <- current_Intervall + 1 
     current_number <- all_list[[current_Intervall]][1] 
    } 
    } 
    print(current_number) 
} 

stopCluster(cl) 

但是打印输出不打印任何东西,约2分钟后循环不终止。但是这个顺序的例子在几秒钟后仍然存在我认为有什么不对。
另一个问题是:是否有可能重新定义foreach循环中的计数器编号?在上面的while循环中,我可以将计数器“current_number”设置为任意值。但我认为在R中for循环不允许重新定义计数器的编号,对吧?是否有更好的软件包或替代循环来并行化第一个示例?

最好的问候, Brayn

回答

1

如果您在使用并行时要输出的东西,使用makeCluster(no_cores, outfile = "")

+0

谢谢,我会试试这个。 – Brayn

+0

@Brayn如果您对答案感到满意,请验证它。 –