Profiling code in R
Overview
Profiling in R can be performed using the following two functions:
RprofsummaryRprof
The Rprof function
The Rprof function records the call stack to the specified file every interval of seconds. It is also used to start and stop the profiling operation.
Syntax
Rprof(filename = "Rprof.out", append = FALSE, interval = 0.02)
Parameters
filename: This is a file to be used for recording the profiling information.append: This is a boolean field that indicates whether the profiling information is appended to the existing file or be overwritten.interval: The time elapsed between the two consecutive samples. The default value is 20 milliseconds.
The summaryRprof function
The summaryRprof function is used to summarize the information given by the Rprof function.
Syntax
summaryRprof(filename = "Rprof.out")
Parameter
filename: This is aRproffunction output file.
Return value
The function returns the following summary statistics:
| Metric | Description |
|---|---|
| by.self | A DataFrame of time spent in the executing function alone |
| by.total | A DataFrame of total time spent in the function and its callees |
| sample.interval | The sampling time interval (Refer interval parameter of Rprof function) |
| sampling.time | The total time spent in profiling the run |
Code example
Let’s look at the code below:
Rprof(tmp <- tempfile())n = 15if(n<=0){print("Invalid n value")}else{fibo_list <- numeric(n)fibo_list[1] <- 1fibo_list[2] <- 1print(paste("The first",n," fibonacci numbers are as follows:"))if(n == 1) print(fibo_list[1])else if(n == 2) print(fibo_list)else{for (i in 3:10) fibo_list[i] <- fibo_list[i - 1] + fibo_list[i - 2]print(fibo_list)}}Rprof(NULL)summaryRprof(tmp)
Code explanation
- Line 1: We invoke the
Rprof()function with a temporary file. - Lines 2-16: We have defined the logic for finding the first
nnumbers in the Fibonacci sequence. - Line 17: We stop the profiling by invoking
Rprof(NULL). - Line 18: We obtain he profiling summary by invoking the
summaryRprof()function.
Free Resources
Copyright ©2025 Educative, Inc. All rights reserved