mercredi 2 mars 2016

std::this_thread::sleep_for sleeps shorter than expected in VS2015

Let's have the following piece of code, that simply measures the duration of std::this_thread::sleep_for called with 20ms:

#include <iostream>
#include <chrono>
#include <thread>

using namespace std;
using namespace std::chrono;

int main()
{
    for (int i = 0; i < 20; i++)
    {
        auto start = steady_clock::now();
        this_thread::sleep_for(milliseconds(20));
        auto end = steady_clock::now();
        duration<double, milli> elapsed = end - start;
        cout << "Waited " << elapsed.count() << " ms\n";
    }
}

When run as compiled with toolset v120 (VS2013's) I get results as expected, i.e.:

Waited 20.0026 ms
Waited 20.0025 ms
Waited 20.0025 ms
Waited 20.0026 ms
Waited 20.0025 ms
Waited 20.0025 ms
Waited 20.0026 ms
Waited 20.0025 ms
Waited 20.0025 ms
Waited 20.0026 ms

but when run with VS2015's toolset v140, results are somewhat surprising and don't respect the promise from both msdn and cppreference.com sleep_for descriptions (that sleep_for blocks the execution of the current thread for at least the specified sleep_duration). They are as following:

Waited 19.7793 ms
Waited 19.9415 ms
Waited 19.6056 ms
Waited 19.9687 ms
Waited 19.608 ms
Waited 19.589 ms
Waited 20.5435 ms
Waited 19.5669 ms
Waited 19.6802 ms
Waited 19.5381 ms

How its possible and how can I make VS2015's sleep_for to sleep at least as long as expected?

Regards, Dawid

Aucun commentaire:

Enregistrer un commentaire