'how to speed up a for loop with one core in R

How to speed up the following code inside a foreach %dopar%?

it is already embedded inside a paralleled foreach loop. Therefore, it better uses only one core. But Is there any way to reduce its computational time a little bit with single core? Thank you.

n = 1e5
k = 10

mu = 0
sigma = 1
x = matrix(data=NA, nrow=n, ncol=k)

for(j in 1:k) {
    for(i in 1:n) {
        x[i,j] = rnorm(1, mu, sigma)
    }
}
r


Solution 1:[1]

Try this:

f1 = function(){
n = 1000
k = 1000
  
mu = 0
sigma = 1
x = matrix(data=NA, nrow=n, ncol=k)
  
for(j in 1:k) {
   for(i in 1:n) {
    x[i,j] = rnorm(1, mu, sigma)
  }
 }
}


f2 = function(){
  n = 1000
  k = 1000
  
  mu = 0
  sigma = 1
  
  data = rnorm(n*k, mu, sigma)
  x = matrix(data=data, nrow=n, ncol=k)
}
system.time(f1())
system.time(f2())

f2() is almost 32 times faster

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ekapunk