[R] x*x*x*... vs x^n

Tuszynski, Jaroslaw W. JAROSLAW.W.TUSZYNSKI at saic.com
Wed Jun 29 14:24:38 CEST 2005


I tried your code and got different results:
	 system.time(ignore <- f1(a))
	[1] 0.83 0.09 1.08   NA   NA
	> system.time(ignore <- f2(a))
	[1] 0.38 0.01 0.41   NA   NA
	> system.time(ignore <- f3(a))
	[1] 0.32 0.04 0.43   NA   NA

So I tried it again but with a loop and got:

	>  for(i in 1:10) cat(system.time(ignore <- f2(a)), "\n")
	0.36 0.04 0.44 NA NA 
	0.32 0.01 0.34 NA NA 
	0.28 0.03 0.32 NA NA 
	0.29 0.03 0.35 NA NA 
	0.3 0.02 0.32 NA NA 
	0.28 0.03 0.32 NA NA 
	0.3 0.02 0.32 NA NA 
	0.29 0.02 0.34 NA NA 
	0.23 0.03 0.32 NA NA 
	0.42 0 0.45 NA NA  

	> for(i in 1:10) cat(system.time(ignore <- f3(a)), "\n")
	0.19 0.04 0.25 NA NA 
	0.17 0.04 0.25 NA NA 
	0.21 0.02 0.25 NA NA 
	0.21 0.02 0.23 NA NA 
	0.18 0.04 0.23 NA NA 
	0.18 0.05 0.23 NA NA 
	0.18 0.04 0.25 NA NA 
	0.17 0.06 0.23 NA NA 
	0.2 0.02 0.23 NA NA 
	0.14 0.06 0.25 NA NA 

It seems to me that f3 is 50% slower than f2 not 300%.

My System is:
- R version: R 2.1.1
- Operating System: Win XP
- Compiler: mingw32-gcc-3.4.2

Jarek
====================================================\=======

 Jarek Tuszynski, PhD.                           o / \ 
 Science Applications International Corporation  <\__,|  
 (703) 676-4192                                   ">   \
 Jaroslaw.W.Tuszynski at saic.com                     `    \



-----Original Message-----
From: r-help-bounces at stat.math.ethz.ch
[mailto:r-help-bounces at stat.math.ethz.ch] On Behalf Of Robin Hankin
Sent: Wednesday, June 29, 2005 7:32 AM
To: r-help
Subject: [R] x*x*x*... vs x^n

Hi

I have been wondering if there one can speed up calculating small powers of
numbers such as x^8 using multiplication.

In addition, one can be a bit clever and calculate x^8 using only 3
multiplies.

look at this:


 > f1 <- function(x){x*x*x*x*x*x*x*x}
 > f2 <- function(x){x^8}
 > f3 <- function(x){x2 <- x*x;x4 <- x2*x2;return(x4*x4)}

[so f1() and f2() and f3() are algebraically identical]


 > a <- rnorm(1000000)
 > system.time(ignore <- f1(a))
[1] 0.50 0.17 2.88 0.00 0.00

 > system.time(ignore <- f2(a))
[1] 0.31 0.03 1.40 0.00 0.00

 > system.time(ignore <- f3(a))
[1] 0.10 0.07 0.18 0.00 0.00


[these figures show little variance from trial to trial]


I was expecting f2() and f3() to be about the same.
I was not expecting a factor of 3 there!

anyone got any comments?




--
Robin Hankin
Uncertainty Analyst
National Oceanography Centre, Southampton European Way, Southampton SO14
3ZH, UK
  tel  023-8059-7743

______________________________________________
R-help at stat.math.ethz.ch mailing list
https://stat.ethz.ch/mailman/listinfo/r-help
PLEASE do read the posting guide!
http://www.R-project.org/posting-guide.html




More information about the R-help mailing list