簡體   English   中英

為什么我的 test_time 沒有接近 5 秒?

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

我正在嘗試制作一個計時器。 我的操作系統是 Windows。
這是一小段代碼,它給出了一個奇怪的結果。
如果一個線程休眠 1 毫秒並執行 5000 次,那么我預計它大約需要 5 秒。
但我得到的結果是 test_time = 12.8095
不明白為什么?
如何修復代碼,以便獲得可以測量大約 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;

如前所述, sleep_for

至少在指定的 sleep_duration 內阻止當前線程的執行。

您的問題的答案是使用sleep_until

阻塞當前線程的執行,直到達到指定的 sleep_time。

這意味着,取當前時間戳,增加 1 毫秒並休眠直到那個時間。

看:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM