lundi 18 avril 2016

How to test which iterative combinatorics & permutation calculator is the most efficient?

I am trying to test which of the two functions is faster at computing the sum of combinations or permutations.

UPDATE: microbenchmark package seems to be the answer to my original question, but I'd like to know why the switches in combo_beast are cheaper than combo_unicorn...

> microbenchmark(combo_beast(5,'yes','yes'))
Unit: microseconds
                         expr   min    lq    mean median    uq    max neval
 combo_beast(5, "yes", "yes") 8.019 8.354 9.94767  8.688 9.022 32.412   100
> microbenchmark(combo_unicorn(5,'yes','yes'))
Unit: microseconds
                           expr   min    lq     mean median    uq    max neval
 combo_unicorn(5, "yes", "yes") 8.354 8.688 10.63269  9.022 9.357 41.768   100

The first function uses nested switches:

combo_beast <- function(n, order, rep){
  switch(order,
         yes = switch(rep,
                      yes = {
                        y <- 0
                        for(i in 1:n){
                          x <- n^i
                          y <- x + y}
                        return(y)
                      },
                      no = {
                        y <- 0
                        for(i in 1:n){
                          x <- factorial(n + i - 1)/(factorial(i)*factorial(n-1))  
                          y <- x + y}
                        return(y)
                      }
                     ),
         no = switch(rep,
                     yes = {
                        y <- 0
                        for(i in 1:n){
                          x <- factorial(n)/(factorial(n - i))  
                          y <- x + y}
                        return(y)
                      },
                      no = {
                        y <- 0
                        for(i in 1:n){
                          x <- factorial(n)/(factorial(n-i)*factorial(i))
                          y <- x + y}
                        return(y)
                      }
                     )
  )
}

The second function utilizes the if/else if approach:

combo_unicorn <- function(n, order, rep){
  if(order == 'yes' & rep == 'yes'){
    y <- 0
    for(i in 1:n){
      x <- n^i
      y <- x + y}
    return(y)
  } else if (order == 'yes' & rep == 'no'){
    y <- 0
    for(i in 1:n){
      x <- factorial(n + i - 1)/(factorial(i)*factorial(n-1))  
      y <- x + y}
    return(y)
  } else if (order == 'no' & rep == 'no'){
    y <- 0
    for(i in 1:n){
      x <- factorial(n)/(factorial(n-i)*factorial(i))
      y <- x + y}
    return(y)
  } else {
    y <- 0
    for(i in 1:n){
      x <- factorial(n)/(factorial(n - i))  
      y <- x + y}
    return(y)
  }
}

I have tried putting ptm <- proc.time() at the start of either function and proc.time() - ptm at the end, but it keeps returning 0s no matter how large I make n.

Aucun commentaire:

Enregistrer un commentaire