Getting wrong value for Millisecond delay

对着背影说爱祢 提交于 2020-07-22 04:39:09

问题


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.stack.imgur.com/AVZDV.png


回答1:


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.




回答2:


This happens because of 2 things.

  1. waiting is not the only thing you are doing, incrementation and if statement checks also take time.

  2. No clock is perfect

Also if you want an infinite loop while(true) is way better looking



来源:https://stackoverflow.com/questions/62445592/getting-wrong-value-for-millisecond-delay

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!