Profiling code
In the previous section, you learned how to use microbenchmark()
to benchmark expressions. This can be useful when we have several alternative solutions to a problem and want to see which has better performance and when we optimize an expression and want to see whether the performance actually gets better than the original code.
However, it is usually the case that, when we feel the code is slow, it is not easy to locate the expression that contributes most to slowing down the entire program. Such an expression is called a "performance bottleneck." To improve code performance, it is best to resolve the bottleneck first.
Fortunately, R provides profiling tools to help us find the bottleneck, that is, the code that runs most slowly, which should be the top focus for improving code performance.
Profiling code with Rprof
R provides a built-in function, Rprof()
, for code profiling. When profiling starts, a sampling procedure is running with all subsequent code until...