如何在指定的时间内运行循环

问题描述 投票:0回答:1

我想在一段指定的时间内运行一段代码。这似乎不起作用。为什么?

int sec = 5;
auto start = std::chrono::steady_clock::now();
while (std::chrono::duration<double, std::milli>(start - std::chrono::steady_clock::now()).count() < sec * 1000)
{
    // do stuff
};
c++ time chrono
1个回答
6
投票

您的问题似乎是相反的减法:循环执行的持续时间是now() - start,而不是start - now()

顺便说一句,一些代码美化让您考虑:

#include <chrono>

int main() {
    auto now = std::chrono::steady_clock::now;
    using namespace std::chrono_literals;
    auto work_duration = 5s;
    auto start = now();
    while ( (now() - start) < work_duration)
    {
        // do stuff
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.