【发布时间】:2015-08-12 13:26:04
【问题描述】:
我有一个运行很长的循环的 C++ 程序。它有大约 500000 次迭代。 我想每 5% 打印一次进度。
到目前为止,我所拥有的如下。 这样做的问题是它会一遍又一遍地写同一行(0%,%5等)。这是因为在将百分比截断为整数后,有 1000 次迭代将达到 5 的倍数。这使程序明显变慢。
相反,如果我不截断为整数,那么percent % 5.0 的结果不太可能正好是 0。
如何打印对运行时影响最小的进度指示器?
// Counters for progress indicator
int i = 0;
float totalWindows = (float)(win.nX * win.nY);
int percent;
while (win.next() == 0)
{
// Read the data
// Nicely formatted progress indicator
i++;
percent = (i / totalWindows) * 100;
if (percent % 5 == 0)
{
std::cout << "\r" << std::string(percent/5, '|') << percent << "%";
std::cout.flush();
}
}
编辑: 感谢您的回答。我选择了 christophes',它的指令数量最少。 它减少了 25% 的运行时间,非常显着!
【问题讨论】: