简体   繁体   中英

std::this_thread::sleep_for time resolution

So I'm helping my buddy out with some code and we've hit some weirdness in the sleep_for function:

This works, gives an "acceptable" timing of about 16.7ms (acceptable being +/- 2-4ms, but anyway):

int main()
{
    long double milliseconds=16.7*1000;

    auto start=std::chrono::high_resolution_clock::now();
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(std::chrono::duration<long double, std::micro>(1670));
    auto end=std::chrono::high_resolution_clock::now();

    std::cout << "Slept for: "<<std::chrono::duration<float, std::milli>(end-start)<<std::endl;
}

This however, will only give you a minimum of 30ms, works as expected above 30ms:

int main()
{
    long double milliseconds=16.7*1000.0;

    auto start=std::chrono::high_resolution_clock::now();
    using namespace std::chrono_literals;
    std::this_thread::sleep_for(std::chrono::duration<long double, std::micro>(milliseconds*1000.0));
    auto end=std::chrono::high_resolution_clock::now();

    std::cout<<"Slept for: "<<std::chrono::duration<float, std::milli>(end-start)<<std::endl;
}

Does anyone have an explanation for this?

I've tried various castings and different periods, they all end up about the same. Using milliseconds period and above causes a minimum of 30ms, microseconds and below have expected results.

I suspect that there are different code paths that does different clock resolutions and bottoms out or something like that, but why doesn't a variable being multiplied by 1000 to go from 'ms' to 'us' not work? I don't get it.

Apparently this is a Windows API "quirk", calling timeBeginPeriod will set minimum period resolution not only on Win32 API calls that deal with timing, but also stdlib.

The timing with this code is nearly perfect on Linux, naturally.

Thanks to Retired Ninja for the answer!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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