如何并行化while循环? [英] How to parallelize while loops?
本文介绍了如何并行化while循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
iter <- 1000
myvec <- c()
while(is.null(myvec) || nrow(myvec) <= iter){
x = rnorm(10, mean = 0, sd = 1)
if(sum(x) > 2.5){
myvec <- rbind(myvec, x)
}
}
我想并行化上面的 while 循环,在那里我不断迭代,直到在 myvec
中总共有 iter = 1000
个条目.我在这里查看了 this 帖子,但我认为那里的答案不适用以我的例子为例.
I want to parallelize the above while loop, where I keep iterating until I have a total of iter = 1000
entries in myvec
. I checked out this post here, but I don't think the answer there is applicable to my example.
推荐答案
实际上你不需要并行化 while 循环.您可以通过 x
对您的操作进行矢量化,如下所示
Actually you don't need to parallelize the while loop. You can vectorize your operations over x
like below
iter <- 1000
myvec <- c()
while (is.null(myvec) || nrow(myvec) <= iter) {
x <- matrix(rnorm(iter * 10, mean = 0, sd = 1), ncol = 10)
myvec <- rbind(myvec, subset(x, rowSums(x) > 2.5))
}
myvec <- head(myvec, iter)
或
iter <- 1000
myvec <- list()
nl <- 0
while (nl < iter) {
x <- matrix(rnorm(iter * 10, mean = 0, sd = 1), ncol = 10)
v <- subset(x, rowSums(x) > 2.5)
nl <- nl + nrow(v)
myvec[[length(myvec) + 1]] <- v
}
myvec <- head(do.call(rbind, myvec), iter)
我相信,即使您有很大的 iter
,这也会更快.
which would be much faster even if you have large iter
, I believe.
这篇关于如何并行化while循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文