[R] Odp: optimizing speed of calculation (recursive product)
Henrik Bengtsson
hb at stat.berkeley.edu
Wed Sep 3 19:37:28 CEST 2008
Note:
n <- 100;
x <- rnorm(n);
t1 <- system.time({
xp <- prod(x);
xpA2 <- xp/x[n];
xpB2 <- xp/x[1];
});
is calculating the product only once and is *constant in memory*.
With the suggest approach you are not only calculating the same thing
twice but you are also allocating a lot of memory, which is likely to
lead into swapping etc for large vectors;
t2 <- system.time({
xpA <- cumprod(x)[n-1];
xpB <- cumprod(x[-1])[n-1];
});
stopifnot(all.equal(xpA2, xpA));
stopifnot(all.equal(xpB2, xpB));
As already pointed out, the example is not a good one numerically.
My $.02
/Henrik
On Wed, Sep 3, 2008 at 10:25 AM, Wolfgang Raffelsberger
<wraff at titus.u-strasbg.fr> wrote:
> Dear Uwe, Petr and Berend,
> Thank's a lot !!
>
> I just checked and it's
> c(cumprod(a)[M-1],cumprod(a[-1])[M-1]))
>
> that gives an identical result to the my initial loop (at 10x speed of my
> initial loop ... )
>
> Wolfgang
>
> Berend Hasselman a écrit :
>>
>> Petr Pikal wrote:
>>
>>>
>>> Hi
>>>
>>> r-help-bounces at r-project.org napsal dne 03.09.2008 16:39:07:
>>> ....
>>>
>>>>
>>>> In many cases I've noticed that using apply, sapply etc can help
>>>> speeding up processes, but in this case I don't see how I could do so.
>>>>
>>>> a <- runif(10000000,0.5,1.6)
>>>> C <- 2
>>>> M <- 10000000
>>>> system.time( for (i in 1:(M-1)) {C <- C* c(a[i],a[i+1])} )
>>>>
>>>
>>> Maybe simple math? You want last two members of 2*cumprod(a).
>>>
>>> So
>>>
>>>
>>>>
>>>> system.time(2*cumprod(a)[9999999:10000000])
>>>>
>>>
>>> user system elapsed 1.97 0.04 2.00 shall be a little bit
>>> quicker then for cycle. But it is valid only for the above calculation.
>>>
>>>
>>
>> I think
>>
>> 2*c(cumprod(a)[M-1],cumprod(a[-1])[M-1])
>>
>> is the answer.
>>
>> Berend
>>
>
>
> --
> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
> Wolfgang Raffelsberger, PhD
> Laboratoire de BioInformatique et Génomique Intégratives
> CNRS UMR7104, IGBMC 1 rue Laurent Fries, 67404 Illkirch Strasbourg,
> France
> Tel (+33) 388 65 3300 Fax (+33) 388 65 3276
> http://www-bio3d-igbmc.u-strasbg.fr/~wraff
> wolfgang.raffelsberger at igbmc.fr
>
> ______________________________________________
> R-help at 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.
>
More information about the R-help
mailing list