O'Reilly logo

Efficient R optimization by Robin Lovelace, Colin Gillespie

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Code Profiling

Often you will have working code, but simply want it to run faster. In some cases, it’s obvious where the bottleneck lies. Sometimes you will guess, relying on intuition. A drawback of this is that you could be wrong and waste time optimizing the wrong piece of code. To make slow code run faster, it is important to first determine where the slow code lives. This is the purpose of code profiling.

The Rprof() function is a built-in tool for profiling the execution of R expressions. At regular time intervals, the profiler stops the R interpreter, records the current function call stack, and saves the information to a file. The results from Rprof() are stochastic. Each time we run a function R, the conditions have changed. Hence, each time you profile your code, the result will be slightly different.

Unfortunately, Rprof() is not user-friendly. For this reason, we recommend using the profvis package for profiling your R code. profvis provides an interactive graphical interface for visualizing code-profiling data from Rprof().

Getting Started with profvis

After installing profvis (e.g., with install.packages("profvis")), it can be used to profile R code. As a simple example, we will use the movies dataset, which contains information on about 60,000 movies. First, we’ll select movies that are classed as comedies, then plot the year the movie was made verus the movie rating and draw a local polynomial regression line to pick out the trend. The main function from the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required