Search code examples
c++multithreadingvisual-studioc++-chrono

Getting wrong value for Millisecond delay


I am trying to get 1 millisecond delay but i am getting 15 times higher.I have also tried with windows Sleep(1) function which was also giving me the same result.

why am i not getting exact millisecond delay?

Where as it works with 1 second delay.

#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;
        }
    }
}

Output of this program: https://i.sstatic.net/AVZDV.png


Solution

  • You are not getting the expected results, because your expectations are off. sleep_for is not to wait for exact time. From 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.

    Exact timing typically requires dedicated hardware. Expecting 1ms from a desktop pc is rather optimistic.

    On top of that the time you measure is not only from sleep_for.