R-alpha: loop speed

Paul Gilbert pgilbert@bank-banque-canada.ca
Mon, 10 Nov 1997 11:56:06 -0500


I noticed Doug only circulated the following on S-news, but it may be of
interest to R users who don't follow S-news. His findings are certainly
consistent with my own, where my problems often force me into the
element by element type of situation.

Paul Gilbert
_______
At the risk of beating this example to death, I went back and compared
the execution time for the element-by-element method with that of the
indexing method.  At vector sizes of 50000 the indexing method is
close to 500 times faster.

 S-PLUS : Copyright (c) 1988, 1996 MathSoft, Inc.
 S : Copyright AT&T.
 Version 3.4 Release 1 for Sun SPARC, SunOS 5.3 : 1996
 Working data will be in .Data
 > x <- rnorm(50000)
 > y <- rnorm(50000)
 > op <- sample(c("*","+","-","/"), 50000, repl = T)
 > foo <-
 + function(x, y, op)
 + {
 +   z <- x
 +   for(i in seq(along = op))
 +     z[i] <- do.call(op[i], list(x[i], y[i]))
 +   z
 + }
 > unix.time(res1 <-
cbind(x*y,x-y,x+y,x/y)[cbind(seq(along=x),match(op,c("*", "-", "+",
"/")))])
 [1] 0.40000010 0.04999995 0.00000000 0.00000000 0.00000000
 > length(res1)
 [1] 50000
 > unix.time(res2 <- foo(x, y, op))
 [1] 196.23   0.29 199.00   0.00   0.00
 > length(res2)
 [1] 50000
 > all.equal(res1, res2)
 [1] T

It is interesting that the difference in execution speed when using R is

much less than when using S-PLUS.  On this machine (Sun UltraSparc 1
running Solaris 2.5.1) R is somewhat slower than S-PLUS for the
indexing version but close to 10 times faster for the
element-by-element version

 R> unix.time(res1 <-
cbind(x*y,x-y,x+y,x/y)[cbind(seq(along=x),match(op,c("*", "-", "+",
"/")))])
 [1] 1.55 0.07 2.00 0.00 0.00
 R> unix.time(res2 <- foo(x, y, op))
 [1] 23.96  0.05 24.00  0.00  0.00
 R> all(res1 == res2)
 [1] TRUE

--
Douglas Bates                            bates@stat.wisc.edu
Statistics Department                    608/262-2598
University of Wisconsin - Madison
http://www.stat.wisc.edu/~bates/



=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
r-devel mailing list -- Read http://www.ci.tuwien.ac.at/~hornik/R/R-FAQ.html
Send "info", "help", or "[un]subscribe"
(in the "body", not the subject !)  To: r-devel-request@stat.math.ethz.ch
=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=