简体   繁体   中英

Optimization R code - Rcpp

In addition to benchmarking functions, is there any tool in R so we can fetch the biggest bottlenecks in an R code?

I often get very undecided about the computational gain I will get when rewriting the R code in C ++. For example, in a bootstrap where each iteration needs to do an optimization, I do not know if it is useful to use the GSL library to do an optimization of a log-likelihood function, since the optim language function R uses the stats.so file. I noticed this doing stats ::: C_optim .

> stats:::C_optim
$name
[1] "optim"

$address
<pointer: 0x1cb34e0>
attr(,"class")
[1] "RegisteredNativeSymbol"

$dll
DLL name: stats
Filename: /usr/lib/R/library/stats/libs/stats.so
Dynamic lookup: FALSE

$numParameters
[1] 7

attr(,"class")
[1] "ExternalRoutine"  "NativeSymbolInfo"

Looking at the body of the optim function ( edit(optim) ), I see that there is the import of efficient functions implemented in C. For example, there is:

.External2(C_optim, par, fn1, gr1, method, con, lower, 
        upper)

Doubt : To Rcpp users, in your projects, do you normally try to implement all your C++ functions or implement a set of small C++ functions to be used in an R function?

I know it's a pretty general question, but all the functions I use Rcpp always try to implement C++ function from scratch. I felt that I'm programming more in C++ than in R. I sometimes think that I need to program directly in C++.

R has many characteristics that make the language slow for various tasks. I always try to avoid loops and give way to the use of the apply family of functions. However, I often find the R very slow. That way, because I'm very undecided on what's worth optimizing, I end up implementing everything in C++.

If you (generally) code faster in R and feel like writing to much C++ code, I suggest the following approach:

  1. Implement your solution in R.
  2. Only if the R solution is not fast enough, try to optimize it.
  3. The first step in optimization is measuring the performance, ie profile your code.
  4. Once you have identified the bottlenecks you can improve those using, better R code or compiled code.

With experience you might be able to cut some corners, ie know from the beginning that some things in your problem will require compiled code. But that really depends on the kind of problems you are working on.

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