简体   繁体   English

为什么我的 test_time 没有接近 5 秒?

[英]Why am I not getting a test_time close to 5 seconds?

I'am trying to make a time meter.我正在尝试制作一个计时器。 My OS is Windows.我的操作系统是 Windows。
Here is a small piece of code that gives a strange result.这是一小段代码,它给出了一个奇怪的结果。
If a thread sleeps for 1ms and does this 5000 times, then I would expect it to take roughly 5 seconds.如果一个线程休眠 1 毫秒并执行 5000 次,那么我预计它大约需要 5 秒。
But I get as a result that test_time = 12.8095但我得到的结果是 test_time = 12.8095
Do not understand why?不明白为什么?
How can I fix the code so that I get a time meter that can measure durations of about 1 millisecond?如何修复代码,以便获得可以测量大约 1 毫秒持续时间的计时器?

std::atomic_bool work = true;
    size_t cnt{};
    std::chrono::duration<double> operation_time;
    double test_time;
            auto start_time_ = std::chrono::high_resolution_clock::now();
            std::thread counter_ = std::thread([&work, &cnt]() {
                while (work) {
                    std::this_thread::sleep_for(std::chrono::milliseconds(1));
                    cnt++;
                    if (cnt >= 5000)
                        work = false;
                }
                });
            
            if (counter_.joinable())
                counter_.join();
            operation_time = std::chrono::duration<double>(std::chrono::high_resolution_clock::now() - start_time_);
            test_time = operation_time.count();

            std::cout << "test_time = " << test_time << std::endl;

As previously stated, sleep_for如前所述, sleep_for

Blocks the execution of the current thread for at least the specified sleep_duration.至少在指定的 sleep_duration 内阻止当前线程的执行。

The answer to your question would be to use sleep_until您的问题的答案是使用sleep_until

Blocks the execution of the current thread until specified sleep_time has been reached.阻塞当前线程的执行,直到达到指定的 sleep_time。

That means, take the current timestamp, add 1 ms and sleep until that time.这意味着,取当前时间戳,增加 1 毫秒并休眠直到那个时间。

See:看:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM