Skip to content

Instantly share code, notes, and snippets.

@andrie
Last active August 29, 2015 14:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save andrie/df101d1c6806fb3258a4 to your computer and use it in GitHub Desktop.
Save andrie/df101d1c6806fb3258a4 to your computer and use it in GitHub Desktop.
Create a tclktk progressbar to provide feedback when running a parallel job
library(foreach)
library(iterators)
library(doParallel)
library(tcltk)
# Choose number of iterations
n <- 250
# In sequence, without progress bar ---------------------------------------
print("Running sequential task")
time1 <- system.time({
k <- foreach(i = icount(n), .packages = "tcltk", .combine = c) %do% {
Sys.sleep(0.01)
log2(i)
}
})
print(time1)
# In sequence, with progress bar ------------------------------------------
print("Running sequential task with progress bar")
pb <- tkProgressBar("Sequential task", min=1, max=n)
time2 <- system.time({
k <- foreach(i = icount(n), .packages = "tcltk", .combine = c) %do% {
if(!exists("pb")) pb <- tkProgressBar("Sequential task", min=1, max=n)
setTkProgressBar(pb, i)
Sys.sleep(0.01)
log2(i)
}
})
close(pb)
rm(pb)
print(time2)
# Run the loop in parallel ------------------------------------------------
print("Running parallel task with progress bar")
cl <- makeCluster(8)
registerDoParallel(cl)
time3 <- system.time({
clusterExport(cl, c("n"))
k <- foreach(i = icount(n), .packages = "tcltk", .combine = c) %dopar% {
if(!exists("pb")) pb <- tkProgressBar("Parallel task", min=1, max=n)
setTkProgressBar(pb, i)
Sys.sleep(0.01)
log2(i)
}
})
#Stop the cluster
stopCluster(cl)
print(time3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment