2017-07-01 49 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如果您對答案感到滿意,請驗證它。 –