Ken Knoblauch <ken.knoblauch <at> inserm.fr> writes: > > 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. >
and just to follow-up on my own suggestion library(Rcpp) cppFunction(' double ss(NumericVector X){ int n = X.size(); double total = 0; for(int i = 0; i < n; i++) for(int j = 0; j < n; j++) total += (X[i] - X[j]) * (X[i] - X[j]); return total; }' ) system.time(ss(X)) user system elapsed 0.002 0.000 0.002 -- 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 ______________________________________________ R-help@r-project.org mailing list https://stat.ethz.ch/mailman/listinfo/r-help PLEASE do read the posting guide http://www.R-project.org/posting-guide.html and provide commented, minimal, self-contained, reproducible code.