Why time is increasing for the same operation? I was expecting +/- the same time for each n. Thanks in advance. bench <- function(f1, n, ...) { t <- 0 for(i in 1:n) { func <- function(x) x^2 expr <- list(...)[1] f1 <- c("system.time(y <- ", gsub("XXX",expr,f1),")[3]") t1 <- eval(parse(text = f1)) printf("time %d: %f\n", i, t1) t <- t + t1 } t <- t/n printf("mean time: %f", t) } bench("func(XXX)", 10, "1:100")
On Thu, Sep 1, 2011 at 8:10 AM, . . <xkziloj at gmail.com> wrote:> Why time is increasing for the same operation? > > I was expecting +/- the same time for each n. > > Thanks in advance. > > bench <- function(f1, n, ...) { > ?t <- 0 > ?for(i in 1:n) { > ? ?func <- function(x) x^2 > ? ?expr <- list(...)[1] > ? ?f1 <- c("system.time(y <- ", gsub("XXX",expr,f1),")[3]") > ? ?t1 <- eval(parse(text = f1)) > ? ?printf("time %d: %f\n", i, t1) > ? ?t <- t + t1 > ?} > ?t <- t/n > ?printf("mean time: %f", t) > } > bench("func(XXX)", 10, "1:100") >On each iteration f1 gets larger. (Also printf is not defined.) Check out the rbenchmark package. -- Statistics & Software Consulting GKX Group, GKX Associates Inc. tel: 1-877-GKX-GROUP email: ggrothendieck at gmail.com
Do a little debugging on your code (put print(f1)) and you will see that you keep adding to the length of the expression to be evaluated and the results you see are correct. Learn how to debug your functions. On Thu, Sep 1, 2011 at 8:10 AM, . . <xkziloj at gmail.com> wrote:> Why time is increasing for the same operation? > > I was expecting +/- the same time for each n. > > Thanks in advance. > > bench <- function(f1, n, ...) { > ?t <- 0 > ?for(i in 1:n) { > ? ?func <- function(x) x^2 > ? ?expr <- list(...)[1] > ? ?f1 <- c("system.time(y <- ", gsub("XXX",expr,f1),")[3]") > ? ?t1 <- eval(parse(text = f1)) > ? ?printf("time %d: %f\n", i, t1) > ? ?t <- t + t1 > ?} > ?t <- t/n > ?printf("mean time: %f", t) > } > bench("func(XXX)", 10, "1:100") > > ______________________________________________ > R-help at r-project.org mailing list > https://stat.ethz.ch/mailman/listinfo/r-help > PLEASE do read the posting guide http://www.R-project.org/posting-guide.html > and provide commented, minimal, self-contained, reproducible code. >-- Jim Holtman Data Munger Guru What is the problem that you are trying to solve?