我正在尝试在 R 中模拟两个循环索引的不同组合(我使用的是 Windows)。
我认为我的电脑正在同时完成这一切。例如,假设我想列出数字 1 到 10。我的计算机列出它们 1,2,3,4,5,6,7,8,9,10。我认为如果我的计算机拆分负载,以便列出我的计算机上的一个核心(1,2,3,4,5)和列出的第二个核心(6,7,8,9,10),那会更好......然后一切都可以连接在一起,从而节省时间。
这是我的模拟:
lambda <- 1/5
n <- 100000
bus_arrivals <- rexp(n, rate = lambda)
results <- data.frame(
s = numeric(),
t = numeric(),
prob_x_greater_than_t = numeric(),
prob_x_greater_than_s_plus_t_given_x_greater_than_s = numeric())
for (s in seq(1, 10, by = 1)) {
for (t in seq(1, 10, by = 1)) {
# Part 1:
p1 <- sum(bus_arrivals > t) / n
# Part 2:
waited_s <- bus_arrivals[bus_arrivals > s]
p2 <- sum(waited_s > s + t) / length(waited_s)
results <- rbind(
results,
data.frame(
s = s,
t = t,
prob_x_greater_than_t = p1,
prob_x_greater_than_s_plus_t_given_x_greater_than_s = p2
)
)
}
}
有人可以告诉我如何在 R 中并行化此代码,以便可以为当前空闲的核心分配部分工作吗?或者一般来说,有什么方法可以加快这段代码的速度吗?
这是我尝试过的解决方案:
library(foreach)
library(doParallel)
no_cores <- detectCores() - 1
registerDoParallel(cores = no_cores)
lambda <- 1/5
n <- 100000
bus_arrivals <- rexp(n, rate = lambda)
# main function
calc_probs <- function(s) {
results <- data.frame(s = numeric(), t = numeric(), prob_x_greater_than_t = numeric(), prob_x_greater_than_s_plus_t_given_x_greater_than_s = numeric())
for (t in seq(1, 10, by = 0.01)) {
# Part 1:
p1 <- sum(bus_arrivals > t) / n
# Part 2:
waited_s <- bus_arrivals[bus_arrivals > s]
p2 <- sum(waited_s > s + t) / length(waited_s)
results <- rbind(results, data.frame(s = s, t = t, prob_x_greater_than_t = p1, prob_x_greater_than_s_plus_t_given_x_greater_than_s = p2))
}
return(results)
}
# execute in paralel
results <- foreach(s = seq(1, 10, by = 0.01), .combine = rbind) %dopar% calc_probs(s)
我认为这是正确的?它运行得更快并且似乎产生了预期的结果?