获得毫秒延迟的错误值

Getting wrong value for Millisecond delay

我试图获得 1 毫秒的延迟,但我得到了 15 次 higher.I 也尝试了 windows Sleep(1) 函数,这也给了我相同的结果。

为什么我没有得到精确的毫秒延迟?

因为它有 1 秒的延迟。

#include <iostream>
#include <Windows.h>
#include <thread>
#include <chrono>

void counter1();

auto main() -> int
{

    std::thread p(&counter1);
    p.join();
    return 0;
}

void counter1()
{
    int nStep = 0;
    const int STEP = 1000;
    auto start = std::chrono::high_resolution_clock::now();
    for (;;)
    {
        ++nStep; // incrementing every millisecond
        std::this_thread::sleep_for(std::chrono::milliseconds(1));
        if (nStep == STEP) {  // compares at second
            auto duration = std::chrono::high_resolution_clock::now() - start;
            std::cout << "counter took " <<
                std::chrono::duration_cast<std::chrono::seconds>(duration).count()
                << "seconds \n";
            start = std::chrono::high_resolution_clock::now();
            nStep = 0;
        }
    }
}

这个程序的输出:https://i.stack.imgur.com/AVZDV.png

发生这种情况是因为两件事。

  1. 等待不是你唯一要做的事情,递增和if语句检查也需要时间。

  2. 没有完美的时钟

另外,如果你想要一个无限循环,while(true) 更好看

您没有得到预期的结果,因为您的预期不对。 sleep_for 不是等待确切的时间。来自 cppreference:

Blocks the execution of the current thread for at least the specified sleep_duration.

This function may block for longer than sleep_duration due to scheduling or resource contention delays.

The standard recommends that a steady clock is used to measure the duration. If an implementation uses a system clock instead, the wait time may also be sensitive to clock adjustments.

精确计时通常需要专用硬件。预计台式机 1 毫秒是相当乐观的。

最重要的是,您测量的时间不仅来自 sleep_for