Josh Josh - 24 days ago 7
C Question

Display the progress of completion while the program is being executed

I want to display the progress of my C program in percentages while it is running. The actual work in the program whose progress should be measured is confined in a loop. Here is what I tried:

int i;
int to = 100000000;

while (i++ < to) {
printf("\rPercent done: %d", (100 * i)/to);
}

Answer

Might be a dumb question, but how does one display a progress while the program is running?

Not like this.

You have multiple issues:

  • Your i is uninitialized, so the program will print garbage. (Fix: -> int i = 0; instead)
  • Your "progress counter" will only count the progress while in the loop. As soon as Percent done: 100 will be printed, only the loop will be over.
  • You're printing 100 million lines to the console. Maybe think that through again.
  • With (i*100)/to you're hitting integer overflow about half way through, so use i / (to / 100) instead. Notice depending on the compiler the compiler could optimize that out by itself.

A little less obnoxious way would be:

#include <stdio.h>

int main (void) {

    int i = 0;
    int to = 100000000;

    while (i++ < to) {
        if (i % 1000000 == 0) {
            printf("\rPercent done: %d",  i / (to / 100));
        }
        dostuff();
    }
    printf("\rLoop finished");
    return 0;
}

This only prints a console message for every full percent. Still obnoxious that you're getting 100 console messages, but nowhere near as bad as 100.000.000 (!) calls to printf. Still though, that's still a performance impact.