问题
I have three functions doing the same task but in a different way:
Function 1:
f1 <- function(n) {
sum = 0
for(i in 1:n) {
sum <- sum + a(i)
}
return(sum)
}
Function 2:
f4 <- function(n) {
sum = 0
for(i in 1:n) {
sum <- sum + b(i)
}
return(sum)
}
Function 3:
f3 <- function(n) {
#Done using lgamma
sum = 0
for(i in 1:n) {
sum = sum + c(i)
}
return(sum)
}
I need to plot the runtime of these 3 functions over a range of values 1 - n using user time from system.time. How can this be done in R?
回答1:
You could use microbenchmark to time your functions, and ggplot2 to plot. Here is an example:
library(microbenchmark)
library(reshape2)
library(ggplot2)
max_n = 15
results = data.frame(sum_lgamma=numeric(max_n),
sum_log_gamma_recursive = numeric(max_n),
sum_log_gamma_loop = numeric(max_n),
id = seq(max_n))
for(i in 1:max_n)
{
results$sum_lgamma[i] = median(microbenchmark::microbenchmark(sum_lgamma(i))$time)
results$sum_log_gamma_loop[i] = median(microbenchmark::microbenchmark(sum_log_gamma_loop(i))$time)
results$sum_log_gamma_recursive[i] = median(microbenchmark::microbenchmark(sum_log_gamma_recursive(i))$time)
}
results = melt(results, id.vars=c("id"))
ggplot(results, aes(x=id,y=value,color=variable)) + geom_line()
来源:https://stackoverflow.com/questions/48474231/plot-the-run-time-of-three-functions