如何加快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)
 
})

结果表明,大部分时间都花在评估线性回归模型上: enter image description here

如@maarvd所建议,您可以并列以加快速度。但是,并行化每个单个计算效率不高,因为一个计算速度太快(约0.5毫秒),因此您必须为每个工作人员分配成千上万个计算量。我同意@Allan Cameron的观点,这值得吗?