This lesson is being piloted (Beta version)

Profiling the code

Overview

Teaching: 10 min
Exercises: 0 min
Questions
  • How to get the computed time for a chunk of code?

  • How to profile the R code

Objectives
  • Learn system.time() function

  • Learn Rprof() function

Function Dates of system

today_date <- Sys.Date()
print(today_date)
date1 <- as.Date("2017-12-02")
print(date1)
#different between date
print(today_date-date1)

time_now <- Sys.time()
print(time_now)

Computation time for a chunk of code

system.time(Sys.sleep(20))

user: time charged to the CPU for this expr elapsed: “wall clock” time

Profiler

Using profvis() tool

#You need to install profvis, ggplot2 if not installed
library(profvis)
profvis({
  data(diamonds, package = "ggplot2")

  plot(price ~ carat, data = diamonds)
  m <- lm(price ~ carat, data = diamonds)
  abline(m, col = "red")
})

image

Alternatively user can select the chunk of code and Select Profile\Profile Selected Line(s)

image

Using Rprof()

Rprof() # Turn on the profiler
data(diamonds, package = "ggplot2")

plot(price ~ carat, data = diamonds)
m <- lm(price ~ carat, data = diamonds)
abline(m, col = "red")
Rprof(NULL) # Turn off the profiler
summaryRprof()

Key Points

  • system.time()

  • Rprof()