[R] Why is looping in R inefficient, but in C not?
Patrick Burns
pburns at pburns.seanet.com
Sun Jun 26 09:47:40 CEST 2011
Probably the easiest way to think
about it is that most of the extra
time is the overhead of calling a
function. So counting the number
of calls to R functions is going to
tell you how much overhead there is.
(Remember that functions call other
functions.)
On 26/06/2011 08:21, Jeff Newmiller wrote:
> For the same reason the Cray XMP was fast at numerical computations... a loop written in a low level language can be optimized to work faster than one written in a higher level language. The XMP optimized loops into hardware, but R just optimizes them in C code, exposed to the R programmer as vector operations.
> ---------------------------------------------------------------------------
> Jeff Newmiller The ..... ..... Go Live...
> DCN:<jdnewmil at dcn.davis.ca.us> Basics: ##.#. ##.#. Live Go...
> Live: OO#.. Dead: OO#.. Playing
> Research Engineer (Solar/Batteries O.O#. #.O#. with
> /Software/Embedded Controllers) .OO#. .OO#. rocks...1k
> ---------------------------------------------------------------------------
> Sent from my phone. Please excuse my brevity.
>
> Alexander Engelhardt<alex at chaotic-neutral.de> wrote:
>
> Hey,
> I just read another post about calling R from C. Someone on
> stackoverflow (DWin makes me suspect its David W.?) referenced this:
> http://www.math.univ-montp2.fr/~pudlo/R_files/call_R.pdf
> Which made me think: Why is a loop in R bad, but in C not?
>
> And where exactly does looping cost the most? I wrote a piece of code
> for my bachelor's thesis where I loop from 1 to 500, and estimate a
> boosted model in every iteration. The procedure takes 2-6 minutes. In
> this example the loop (instead of some kind of apply()) shouldn't cost
> too much time, right?
> I suspect it's way worse if someone would loop from 1 to 10000 and
> perform only a small task (a mean(), for example) in each loop. Can
> someone confirm this?
>
> Regards,
> Alex
>
> _____________________________________________
>
> 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.
>
>
> [[alternative HTML version deleted]]
>
> ______________________________________________
> 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.
>
--
Patrick Burns
pburns at pburns.seanet.com
twitter: @portfolioprobe
http://www.portfolioprobe.com/blog
http://www.burns-stat.com
(home of 'Some hints for the R beginner'
and 'The R Inferno')
More information about the R-help
mailing list