Timing promises in R

44 views Asked by At

I'm timing a simple function that waits for 1 second and then prints a number. Wrapping it with a promise I was expecting that the promises would run after the timing was complete - which doesn't seem to be what is happening. My understanding is that promises allow the next code to run without completing. What am I missing?

library(tictoc)
library(promises)
library(purrr)

slow_fun <- function(x){
  Sys.sleep(1)
  print(paste("Test:", x))
}

promise_fun <- function(x){
  future_promise(
    slow_fun(x)
  ) 
}

my_nums <- 1:5

{
  tic("Sequential run")
  my_nums %>% map(slow_fun)
  toc()  
}
# Sequential run: 5.09 sec elapsed

{
  tic("Promise run")
  my_nums %>% map(promise_fun)
  toc()  
}
# Promise run: 5.46 sec elapsed  <---- was expecting < 1 second
# with print statements occuring after the timer finished 
# (they occurred before the timer).
0

There are 0 answers