简体   繁体   中英

Caching intermediate results in Rcpp objects

I'm currently trying to speedup an optimisation procedurę which uses Rcpp to calculate the objective function. My current setup is similar to this:

largeConstantVector <- readVector()
result <- optim(..., eval=function(par) evalRcpp(par, largeConstantVector)) 

and the evalRcpp function

double evalRcpp(NumericVector par, NumericVector constVector){
    NumericVector parT = transform(par)
    NumericVector constVectorT = transform(constVector)

    return aggregate(parT, constVectorT)
}

What I would like to do is to calculate NumericVector constVectorT = transform(constVector) only once and keep the result in a C++ object and only use a reference to that object on R's side. So the procedurę would be similar to this:

largeConstantVector <- readVector()
objReference <- calculateCommonStuff(largeConstantVector)
result <- optim(..., eval=function(par) evalRcpp(par, objReference)) 

and the evalRcpp function

double evalRcpp(NumericVector par, const SomeClass& objRef){
    NumericVector parT = transform(par)
    NumericVector constVectorT = objRef.constVectorT

    return aggregate(parT, constVectorT)
}

Is such an approach possible using Rcpp? Will it be possible to prevent unnecessary computation and data copying (that is keep the itermediate data "on the C++ side")?

Thanks in advance.

Yes, it is possible to keep the itermediate data "on the C++ side" as you say, but that is more of a C++ program design issue than anything particular to Rcpp.

Create a class with private state data, use a function to create the class object, then have it update during the iterations.

Rcpp will help to easily call those member functions, but it doesn't create the rest of the framework for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM