绘制三个函数的运行时间 [英] Plot the run time of three functions
本文介绍了绘制三个函数的运行时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有三个函数执行相同的任务,但方式不同:
I have three functions doing the same task but in a different way:
功能一:
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)
}
我需要使用 system.time
中的 user
时间在 1 - n 的值范围内绘制这 3 个函数的运行时间.如何在 R 中做到这一点?
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?
推荐答案
您可以使用 microbenchmark
为您的函数计时,并使用 ggplot2
进行绘图.下面是一个例子:
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()
这篇关于绘制三个函数的运行时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文