Measuring and Benchmarking Code Execution Time in R
Overview
Matlab R is certainly a programming language specialized in statistical analysis, but like all languages, it is not indifferent to speed. Even if speed is not a forte, one should be able to benchmark. In R, you can simply measure time by putting the entire code inside system.time({})
.
Example
Below is the code that implements the Sieve of Eratosthenes in R and checks if numbers less than or equal to $2*10^{5}$ and odd, are prime or not by extracting 30 of them, followed by measuring its execution time.
eratosthenes<-function(n){
residue<-2:n
while(n %in% residue){
p<-residue[1]
residue<-residue[as.logical(residue%%p)]
}
return(p)
}
set.seed(150421)
test = sample(2*1:10^5+1,30)
system.time({
for(n in test){
print(paste0("eratosthenes(",n,") = ",eratosthenes(n)))
}
print("계산 끝")
})
The execution result is as follows.