function in R which also returns the execution time itself

4

I know there is Rprof (), but it seems rather inaccurate compared to the microbenchmark (). However, if I want to use the microbenchmark () I have to call the function 2 times, one to have the output of it and another to run the time of it (which seems to me quite unfeasible)

I do not know how to call the function only once and have the normal output of the function as well as the precise execution time.

The function is not this, but here is an example of my problem:

teste <- function(x){

  Rprof()
  x <- x+2
  Rprof(NULL)

  return(summaryRprof())
}
guarda_x_e_tempo <- teste(2)

or

teste <- function(x){
  x <- x+2
  return(x)
}
guarda_x <- teste(2)
guarda_tempo <- teste(2)
    
asked by anonymous 02.06.2018 / 23:42

3 answers

1

See if the following is what you want. The result of the base R function proc.time is obtained at the first instruction of the function teste and then subtracted from proc.time at the end.

teste <- function(x){
  ini <- proc.time()
  x <- x + 2
  list(result = x, tempo = proc.time() - ini)
}

guarda_x_e_tempo <- teste(2)

guarda_x_e_tempo
#$'result'
#[1] 4
#
#$tempo
#   user  system elapsed 
#      0       0       0

Now another function, more time consuming.

teste2 <- function(x, n = 1e6){
  ini <- proc.time()
  for(i in seq_len(n)) x <- x + 2
  list(result = x, tempo = proc.time() - ini)
}

teste2(2)
#$'result'
#[1] 2000002
#
#$tempo
#   user  system elapsed 
#   0.08    0.00    0.08 
#

Another way is by the expression to time in system.time . This allows you to time the execution without modifying the functions.

teste3 <- function(x, n = 1e6){
  for(i in seq_len(n)) x <- x + 2
  x
}

system.time(teste3(2))
# usuário   sistema decorrido 
#   0.048     0.000     0.049
    
03.06.2018 / 12:05
2

Adenilson, how are you?

I believe the system.time function meets your need:

funcao_exemplo <- function(x) {
  print(x)
}

system.time(funcao_exemplo("Hello World"))
    
04.06.2018 / 16:51
2

The precision of microbenchmark is to rotate the functions several times and thus avoid being influenced by possible computer crashes that could affect the execution time. When you run microbenchmark it runs by default the function 100x to be able to calculate median, median, runtime echo.

That being said, microbenchmark is not suitable for what you want to do.

I think the other answers already have good solutions, but I think an elegant way to do this would be to create a function like this:

crono <- function(f) {
  function(...) {
    exec_time <- system.time({res <- f(...)})
    list(
      exec_time = exec_time,
      res = res
    )
  }
}

We call this type of function Function Operators .

With it you can create versions of your functions that are timed, for example:

crono_mean <- crono(mean)
crono_mean(1:10000000)

That would result in:

$exec_time
   user  system elapsed 
  0.034   0.018   0.061 

$res
[1] 5e+06
    
07.06.2018 / 14:18