Skip to content
Prev 1199 / 10988 Next

[Rcpp-devel] [R] fast rowCumsums wanted for calculating the cdf

Hi,

This would probably deserve some abstraction, we had C++ versions of 
apply in our TODO list for some time, but here is a shot:


require( Rcpp )
require( inline )


f.Rcpp <- cxxfunction( signature( x = "matrix" ), '

     NumericMatrix input( x ) ;
     NumericMatrix output  = clone<NumericMatrix>( input ) ;

     int nr = input.nrow(), nc = input.ncol() ;
     NumericVector tmp( nr );
     for( int i=0; i<nc; i++){
         tmp = tmp + input.column(i) ;
         NumericMatrix::Column target( output, i ) ;
         std::copy( tmp.begin(), tmp.end(), target.begin() ) ;
     }
     return output ;


', plugin = "Rcpp" )

f.R <- function( x ){
     t(apply(probs, 1, cumsum)) #SLOOOW!
}



  probs <- t(matrix(rep(1:100),nrow=10)) # matrix with row-wise probabilites
stopifnot( all.equal( f.R( probs ), f.Rcpp( probs ) ) )

require( rbenchmark )
probs <- t(matrix(rep(1:10000000), nrow=10)) # matrix with row-wise 
probabilites

bm <- benchmark(
     f.R( probs ),
     f.Rcpp( probs ),
     columns=c("test", "elapsed", "relative", "user.self", "sys.self"),
     order="relative",
     replications=10)
print( bm )


I get this on my iMac with R 2.12.0 and Rcpp as just released to CRAN.

$ Rscript cumsum.R
            test elapsed relative user.self sys.self
2 f.Rcpp(probs)   4.614  1.00000     4.375    0.239
1    f.R(probs)  68.645 14.87755    67.765    0.877

When we implement "apply" in C++, we will probably leverage loop 
unrolling to achieve greater performance.

Romain

Le 15/10/10 14:34, Douglas Bates a ?crit :