mercredi 2 novembre 2022

how does std::this_thread::yield() works

std::this_thread::yield() leaves current CPU time slice to other threads/process. On Windows platform, each CPU time slice should cost 2~10ms. Which means the time gap should be larger than 2~10ms when I use std::this_thread::yield() in the while 1 loop.

I create a test program `

void thread_function_2() {
    double dt;
    LARGE_INTEGER nFreq;
    QueryPerformanceFrequency(&nFreq);

    LARGE_INTEGER tstart;
    LARGE_INTEGER tend;
    QueryPerformanceCounter(&tstart);

    for (int a =0; a< 100; a++)
    {
        std::this_thread::yield();
    }
    QueryPerformanceCounter(&tend);
    cout << "-----------------hit 100 times yield cost time-----------------" << endl;
    dt = (tend.QuadPart - tstart.QuadPart) / (double)nFreq.QuadPart;
    cout << "Total time :" << dt * 1000000 << "us" << endl;//dt
}



int main()
{
        std::thread thread_2(thread_function_2);
    system("pause");
        return 1;
}


`

The output is -----------------hit 100 times yield cost time----------------- Total time :9.9us

That means call the 100times std::this_thread::yield() totally cost 9.9us.

My understanding is each time I call the std::this_thread::yield(), it should leave the CPU time slice, at least const 2ms, then it should cost at least 200ms for the 100 cycle std::this_thread::yield().

Aucun commentaire:

Enregistrer un commentaire