gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:38:46 31 4
gpt4 key购买 nike

我有一个带有长时间运行循环的 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% 的运行时间,非常重要!

最佳答案

考虑到 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();
}

}

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

关于C++ 打印进度,对运行时的影响最小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31966598/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com