Skip to content

Instantly share code, notes, and snippets.

@luiarthur
Last active September 26, 2022 17:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luiarthur/9e1a3203d97044a7fc005e32bf4d7459 to your computer and use it in GitHub Desktop.
Save luiarthur/9e1a3203d97044a7fc005e32bf4d7459 to your computer and use it in GitHub Desktop.
Basic Progress Bar for R
ProgressBar = function(num_steps, freq=0.2) {
tic = Sys.time()
init = Sys.time()
current_step = 0
update = function() {
current_step <<- current_step + 1
toc = Sys.time()
if ((toc - tic > freq) || (current_step == num_steps)) {
.speed = current_step / as.numeric(toc - init)
speed = round(ifelse(.speed > 1, .speed, 1 / .speed))
speed_units = ifelse(.speed > 1, "it/s", "s/it")
cat(
"\rProgress: ", current_step, "/", num_steps,
" | speed: ", speed, speed_units,
sep = ""
)
tic <<- toc
if (current_step == num_steps) {
cat(" (Wall: ", toc - init, "seconds.)\n")
}
flush.console() # needed for jupyter notebooks.
}
}
list(update = update, iters = 1:num_steps)
}
@luiarthur
Copy link
Author

luiarthur commented Sep 21, 2022

Example usage:

pb = ProgressBar(100000L)
for (j in pb$iters) {
    pb$update()
}

@luiarthur
Copy link
Author

luiarthur commented Sep 21, 2022

Note: The progress bar has an approximately 2.5e-05 seconds overhead, per iteration.

@luiarthur
Copy link
Author

Can be installed with:

devtools::source_gist("https://gist.github.com/luiarthur/9e1a3203d97044a7fc005e32bf4d7459")

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment