A simple single threaded solution would be to check every x (e.g. 1000) loop iterations wether your desired next status milestone (e.g. 1%) has been reached and print out a statement then. Optionally check wether at least (half) a second has passed.
#include <sys/time.h>
struct timeval last, now;
gettimeofday(&last, NULL);
size_t lastprint = 0;
size_t i;
for (i = 0; i < num_iterations; i++) {
if (!(i & 0x3FF)) { // every 1024 iterations
if ( 100 * (i - lastprint) / num_iterations >= 1) { // at least one percent passed
gettimeofday(&now, NULL);
if (now.tv_usec - last.tv_usec + (1000000 * (now.tv_sec - last.tv_sec)) > 500000) { // at least half a second passed
// print status
last = now;
lastprint = i;
}
}
}
// do work
}
Depending on how long a loop iteration takes it may or may not have performance impacts. As a rule of thumb: if your loop takes longer then 20 nanoseconds to execute you will be fine with this.
If your loops are that small that you can't afford to have an extra branch in them for status messages then
- You should consider parallelising your code first
- You should put the iteration index into a shared variable and check it with a status printing thread every (half a) second and print status messages like this.