Search code examples
windowsperformancewinapidelayclock

So is Sleep() and this the same?


So, are these two the same? Using delay CPU usage is crazy in task manager.. is this the same case as the System Idle Process?

#include <iostream>
#include <time.h>
//#include <windows.h>

int delay(long int time)
{
    clock_t beginning = clock();
    while(clock() - beginning < time) {}
    return 0;
}

int main()
{
    clock_t beginning = clock();

    begin:

    std::cout << "delay this by 1000ms\n";

    //Sleep(1000);
    delay(1000);

    goto begin; //i know, i know

    return 0;
}

Solution

  • This is called "busy waiting" and is most definitely not the same as calling Sleep(). Sleeping will deschedule your process so that other processes get a chance to run; busy waiting will just keep the CPU busy doing nothing useful, and slowing down the entire system.

    The "System Idle Process" is doing the same thing, but it only gets scheduled when no other process has work to do. It is probably also more power-efficient than the loop you wrote. Wikipedia has interesting details on the how and why.