如何解决如何加快R中的循环速度?
FServerSocket->Free();
上面是一个简单的线性回归模型,具有1000万次迭代。我在寻求帮助以加快循环速度。该代码基本上以y2 x2 + 0.2 x2 + rnorm(n,mean = 0,sd = sdu)运行,然后将其用于计算vbeta2
的平均值>解决方法
您可以使用profvis
来确定将处理器时间花费在哪里:
library(profvis)
profvis({
set.seed(155656494)
#setting parameter values
n<-500
sdu<-25
beta0<-40
beta1<-12
# Running the simulation again
# create the x variable outside the loop since it’s fixed in
# repeated sampling
x2 <- floor(runif(n,5,16))
# set the number of iterations for your simulation (how many values
# of beta1 will be estimated)
nsim2 <- 1000
# create a vector to store the estimated values of beta1
vbeta2 <- numeric(nsim2)
# create a loop that produces values of y,regresses y on x,and
# stores the OLS estimate of beta1
for (i in 1:nsim2) {
y2 <- beta0 + beta1*x2 + 0.2*x2 + rnorm(n,mean=0,sd=sdu)
model2 <- lm(y2 ~ x2)
vbeta2[i] <- coef(model2)[[2]]
}
mean(vbeta2)
})
如@maarvd所建议,您可以并列以加快速度。但是,并行化每个单个计算效率不高,因为一个计算速度太快(约0.5毫秒),因此您必须为每个工作人员分配成千上万个计算量。我同意@Allan Cameron的观点,这值得吗?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。