I have finished a code including a for loop with thousands of times calculations and I want to create a progress bar for the counter. I tried several codes which could be found on the web but most of them were problematic.
I appreciate it if you guys offer me a code maybe an inline method to create this.
if you know the total number of iterations, it should just be % based. If in a gui, with a progress bar widget, its literally progbar.setposition(percentage done) or very nearly this in .net/MFC.
if doing it by hand, you can just write the % out every so often.
Here's how I did it with text recently. The code processes a large collection of files and prints "10% 20% 30% ... 100%".
TargetPct is the next percentage mark that it will print. targetCount is the value of i that represents that target percentage. Since I'm going through a vector, the targetCount is one less than you might expect: e.g., if there are 100 items, then targetCount will be 9, 19, 29, ... 99 rather than 1, 10, 20, ..., 100. If I used the latter then it would never print 100% because the loop exits at 99 instead of 100.
The size of the array isn't going to be huge so I don't have to worry about overflow when computing targetCount
1 2 3 4 5 6 7 8 9 10 11 12 13
int targetPct = 10;
int targetCount = files.size() * targetPct / 100; - 1;
if (files.empty() || !hdl)
rc = -1;
for (size_t i=0; rc == 0 && i<files.size(); ++i) {
if (i == targetCount) {
cerr << targetPct << "% ";
targetPct += 10;
targetCount = files.size() * targetPct / 100 - 1;
}
...
}