我有三个函数以不同的方式执行相同的任务:
功能1:
f1 <- function(n) {
sum = 0
for(i in 1:n) {
sum <- sum + a(i)
}
return(sum)
}
功能2:
f4 <- function(n) {
sum = 0
for(i in 1:n) {
sum <- sum + b(i)
}
return(sum)
}
功能3:
f3 <- function(n) {
#Done using lgamma
sum = 0
for(i in 1:n) {
sum = sum + c(i)
}
return(sum)
}
我需要使用来自user
的{{1}}时间,在1到n的值范围内绘制这3个函数的运行时间。怎么能在R?
答案 0 :(得分:4)
您可以使用microbenchmark
为您的功能计时,并ggplot2
进行绘图。这是一个例子:
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()