C++打印进度,对运行时影响最小

jra*_*amm 5 c++ console progress

我有一个带有长循环的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();
    }



}
Run Code Online (Sandbox Code Playgroud)

编辑:谢谢你的答案.我已经和christophes一起去了,其中只有最少的指令.它削减了25%的运行时间,非常重要!

Chr*_*phe 2

考虑到这totalWindows似乎保持不变,并且integer递增/递减可能比许多double转换为 int 的操作更快,我建议:

// Counters for progress indicator
int i = 0;
float totalWindows = (float)(win.nX * win.nY);
int increment5 = 0.05 * totalWindows; // how many iterations does 5% represent ? 
int countdown = increment5;   // decrement countdown instead of modulo
int percent5 = 0;  // number of elements in the progress bar (1 means 5%)

while (win.next() == 0)
{
    // Read the data

    // Nicely formatted progress indicator
    i++;
    if (--countdown == 0)
    {
            percent5++;
            std::cout << "\r" << std::string(percent5, '|') << percent5*5 << "%";
            countdown = increment5;  
            std::cout.flush();
    }

}
Run Code Online (Sandbox Code Playgroud)

如果您担心累积舍入不能用于显示进度,您始终可以选择计算 -block 中的精确值if:计算将仅每 5% 执行一次,而不是每次迭代执行一次。