c++ - 如何在长时间计算中在 C++ 中每 3 秒获取一次进度更新

标签 c++

我有一个程序可以运行 10 多个小时的计算。这是一项逐项的任务,逐行读取文件并对输入进行计算。此刻它保持沉默 10 小时,然后吐出一条“已用时间:xxx 分钟”消息。

我想随时获取更新,但我也想对问题进行过度设计,以便定期获取更新。显然我可以做一些事情

if (++tasks_processed % 100000 == 0)
    cout << tasks_processed << " entries processed...\n";

但我预计我可能会在不久的将来改进我的算法,或者处理器/磁​​盘速度的简单进步将导致我的程序在 2-3 年的时间内每秒发送十几个这样的垃圾邮件。因此,我希望能够在未来证明我的报告间隔。

现在替代方案是在我说的地方有一些基于 chrono 的解决方案

high_resolution_clock::time_point t_start = high_resolution_clock::now();

while (...) {
    processing...

    high_resolution_clock::time_point t_now = high_resolution_clock::now();
    auto duration = duration_cast<seconds>(t_now - t_start).count();
    if (duration >=3)
        cout << tasks_processed << " entries processed...\n";
}

但这会为紧密循环增加很多开销。是否有任何其他设施我可以利用来达到预期的效果?

最佳答案

检查这个不言自明的伪代码作为解决方案

void LongComputation(std::atomic<bool>& running, std::atomic<float>& progress)
{
    // do long computation
    while (running)
    {

        //update progress 
    }
}

void ProgressCounter(std::atomic<bool>& running, std::atomic<float>& progress)
{
    while (running)
    {
        std::cout << progress << "\n";
        std::this_thread::sleep_for(std::chrono::seconds(3));
    }
}

int main() {

    std::atomic<bool> running{true};
    std::atomic<float> progress{0};

    std::thread t1([&running, &progress]() { LongComputation(running, progress); });
    std::thread t2([&running, &progress]() { ProgressCounter(running, progress); });

    //simulating GUI loop 
    while (!getch())
    {

    }

    running = false;
    t1.join();
    t2.join();
    return 0;

}

关于c++ - 如何在长时间计算中在 C++ 中每 3 秒获取一次进度更新,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49524558/

相关文章:

c++ - gcov 没有生成所有 gcda 文件

c++ - 指针和数据之间的 union ,可能存在的陷阱?

c++ - (*object)[0] 和 (*object)[1] 有什么区别

c++ - 如何从文件中读取哈夫曼树频率

c++ - 9 月 5 日之后每天执行一个 Action

c++ - 使用 CMake 构建 GStreamer 会导致 SDP 和 WebRTC 无法解析的外部符号错误

c++ - 令人困惑的 C++ 赋值

c++ - Mat_<float> 到 OutputArray

c++ - 从(声明) header 将参数写入文件

c++ - 类内的typedef