[Rcpp-devel] R vectorisation vs. C++ vectorisation

Romain Francois romain at r-enthusiasts.com
Wed Nov 21 14:00:09 CET 2012


Le 21/11/12 13:22, Darren Cook a écrit :
> I wrote:
>>>> P.S. I don't think the sugar versions can be made any quicker, because
>>>> they have to allocate intermediate vectors, and do more memory copies.
>
> By "sugar versions" I meant vacc4() vs. vacc3()
> (https://gist.github.com/4111256) not pmin() and friends. The vacc4()
> code looks like:
>
>    NumericVector p(age.size());
>    p = 0.25 + 0.3 * 1 / (1 - exp(0.04 * age)) + 0.1 * ily;
>    p = p * ifelse(female, 1.25, 0.75);
>    p = pmax(0,p);
>    p = pmin(1,p);
>
> Each operation copies the whole NumericVector each time, each of which
> needs a memory allocation.

Nope. The NumericVector::operator=( sugar expression ) is used and 
memory for p is allocated just once, when p is constructed with this lne:

  NumericVector p(age.size());

None of the "p = ..." lines allocate memory for p.

The differences in timing don't come from additional memory allocations.

Although this thread allows me to identify something that can be 
improved in the operator=.

> vacc3a() does the same pipeline of operations on a single double, which
> is therefore likely to be a single CPU register, and the whole of
> vacc3a() will be inlined in vacc3().
>
>
>> Also, I'm probably goinf to add a function that does the equivalent of :
>>
>> pmax( b, pmin( a, x ) )
>>
>> I'm thinking of naming it pminmax. Any better idea ?
>
> I'd expect a function called minmax() to return two values, the min and
> max function. The "p" prefix is too subtle for me :-)
>
> How about clip():
>     p = clip(p, 0.0, 1.0);


I like "clip".


> This is such a common operation that I'm surprised R doesn't already
> have a function like this!
>
> Darren
>
>


-- 
Romain Francois
Professional R Enthusiast
+33(0) 6 28 91 30 30

R Graph Gallery: http://gallery.r-enthusiasts.com
`- http://bit.ly/SweN1Z : SuperStorm Sandy

blog:            http://romainfrancois.blog.free.fr
|- http://bit.ly/RE6sYH : OOP with Rcpp modules
`- http://bit.ly/Thw7IK : Rcpp modules more flexible



More information about the Rcpp-devel mailing list