[R] speeding up

Ken Knoblauch ken.knoblauch at inserm.fr
Mon Oct 21 22:49:45 CEST 2013


Bos, Roger <roger.bos <at> rothschild.com> writes:
> I am using a sum of squared differences in the 
objective function of an optimization problem I am 
doing and I
> have managed to speed it up using the
 outer function versus the nested for loops, but my 
suspicion is that
> the calculation could be done even quicker.  
Please see the code below for a simple example.  If 
anyone can

> point out a faster way I would appreciate it greatly.
> 
> Thanks,
> 
> Roger
> 
> X <- runif(1000)
> 
> now <- proc.time()
> ans <- 0
> for (i in 1:length(X)) {
>   for (j in 1:length(X)) {
>     ans <- ans + (X[i]-X[j])*(X[i]-X[j])
>   }
> }
> ans
> speed <- proc.time() - now; cat(" That took ", 
round(speed[3],1), " secs.\n", sep="")
> 
> now <- proc.time()
> gg <- outer(X, X, FUN="-")
> sum(gg*gg)
> speed <- proc.time() - now; cat(" That took ", 
round(speed[3],1), " secs.\n", sep="")
> 
> 

system.time(
for (i in 1:length(X)) {
  for (j in 1:length(X)) {
    ans <- ans + (X[i]-X[j])*(X[i]-X[j])
  }
})
   user  system elapsed 
  2.241   0.009   2.293 

system.time(2 * sum(c(dist(X))^2))

   user  system elapsed 
  0.038   0.002   0.040 

and then there is Rcpp if you want to add
some extra grease.

-- 
Kenneth Knoblauch
Inserm U846
Stem-cell and Brain Research Institute
Department of Integrative Neurosciences
18 avenue du Doyen Lépine
69500 Bron
France
tel: +33 (0)4 72 91 34 77
fax: +33 (0)4 72 91 34 61
portable: +33 (0)6 84 10 64 10
http://www.sbri.fr/members/kenneth-knoblauch.html



More information about the R-help mailing list