The profvis
package is a powerful tool for line profiling in R.
This package is provided by the RStudio team, and its most appreciated feature is the interactive report that is automatically produced, representing a really effective way of visualizing and investigating time resources requested by each part of your code.
Since the lineprof
package is not hosted on CRAN, but on GitHub, we first need it to install the devtools
package in order to leverage the install_github
function provided by this package.
Moreover, we will use the ggmap
package to build the example to be profiled:
install.packages(c("devtools","ggmap")) library(devtools) install_github("rstudio/profvis") library(profvis) library(ggmap)
profvis
object containing the code to be profiled. Run the following piece of code, initializing the report
object.ggmap
recipe in Chapter 3, Basic Visualization Techniques; refer to the recipe for further details:report <- profvis ({ library(ggmap) trip <- (route(from = "rome", to = "milan",structure = "route", output = "simple")) segment <- c() for(i in 1:nrow(trip)) { if(i == 1){segment[i] <- 1}else { if( i %% 2 != 0 ) { segment [i] <- i-segment[i-1]}else { segment [i] <- i/2 } } } } segment_couple <- c(0,segment[-length(segment)]) trip$segment <- segment trip$segment_couple <- segment_couple route_map <- get_map("italy",zoom = 6) ggmap(route_map) + geom_point(aes(x = lon, y = lat, size = 5, colour = hours),data = trip) + geom_line(data = trip,aes(group = segment)) + geom_line(data = trip, aes(group = segment_couple)) })Print the object runing print(report)
This will open a web browser window, showing an interactive profiling report similar to the following:
In the preceding screenshot, on the left-hand side, you can find your code produced line by line, where each line has, on the right-hand side, a count of the required milliseconds for running and a count of the proportion of the time on the total running time. On the right-hand side part of the report, a barchart-like interactive plot is produced, where the bottom line represents the first function that was called and the upper bars represent the functions called by those first functions. You can hide lines of code having zero running time. On the top-right corner of the left-hand side part of your report, you can find a Settings control. Selecting it will open the following menu:
Selecting the checkbox next to Hide lines of code with zero time will result in hiding of all the lines of code that have a running time less than a millisecond:
Running cmd + S on Mac devices, or Ctrl + S on Windows devices, will let you save your report as a fully functional web page: