6

The Title says it all. I tried looking for this but to no avail.

Basically, I am running a For Loop with 1000 iterations, and I would like to write a function that shows/prints the progression of the simulation every 10 iterations.

4 Answers4

14

How about the progress bar that is built-in with R? It prints a progress bar on the console, and let's you monitor the progress through the iterations. Unfortunately, this does not quite answer the question, because it gets updated every round of a loop, and if the number of iterations is not known beforehand, it doesn't quite get you where you want. Progress bar works as follows:

# Number of iterations
imax<-c(10)
# Initiate the bar
pb <- txtProgressBar(min = 0, max = imax, style = 3)
# Iterations
for(i in 1:imax) {
   Sys.sleep(1) # Put here your real simulation
   # Update the progress bar
   setTxtProgressBar(pb, i)
}
# Finally get a new line on the console
cat("\n")

You can certainly accomplish what you're looking after with modulus. Here's an example for the for-loop:

for(i in 1:1000) {
   # Modulus operation
   if(i %% 10==0) {
      # Print on the screen some message
      cat(paste0("iteration: ", i, "\n"))
   }
   Sys.sleep(0.1) # Just for waiting a bit in this example
}

Would either one of these work for you?

1

You likely want to use a modulus operator

If you base check your iterator in the loop and mod it against 10 then you can have it perform some action every time the iterator is evenly divisible by 10.

0

Depending on what language you're using, your syntax may vary slightly, but it sounds like a problem for modulus division. Assuming you have access to your loop counter, you can divide it by ten and check your remainder to see if your counter is divisible by ten.

Community
  • 1
  • 1
Ben Delaney
  • 1,082
  • 11
  • 19
0

Although you already accepted an answer I was thinking I would still post my view on it. You can use windows progress bar to monitor your progress. There is a nice example here For Loop Tracking (Windows Progress Bar). Below is my version of the progress bar, however it monitors overall progress.

my_progress <- function(m)
{
  pb <- winProgressBar(title="Example progress bar", label="0 Completed", min=0, max=m, initial=0)
  for(i in 1:m) {
    Sys.sleep(0.01)
    setWinProgressBar(pb, i/(100)*100, label=round((i/100)*100))
  }
  close(pb)
  message("Tesk Completed")
}

my_progress(1000)
Pork Chop
  • 28,528
  • 5
  • 63
  • 77