Instead of calculating the percentage each time, you can calculate what 5% of the total amount is and use it directly.
Consider this simplified example:
int main(int argc, char * argv) { int total = 50000; int total_percent_stop = total * 5 / 100; //Set the percentage here. for (int i = 0; i < total; i++) { if (i % total_percent_stop == 0) { printf("%d percent done\n", (i / total_percent_stop) * 5); } } }
If the performance of this code is very important to you, you can avoid the relatively expensive division operations by doing something like this (due to some readability).
int main(int argc, char * argv) { int total = 50000; int total_percent_stop = total * 5 / 100; //Set the percentage here for (int i = 0, percent_counter = 0, n_percent = 0; i < total; i++, percent_counter++) { if (percent_counter == total_percent_stop) { percent_counter = 0; n_percent++; printf("%d percent done\n", n_percent * 5); } } }
On my machine, with sufficiently large values, the second amount is much faster. When I changed everything to unsigned long longs and set the total to 5 billion, the second took 9.336 seconds and the first took 40.159 seconds
source share