Sleep() function usage

Aneesh Narayanan picture Aneesh Narayanan · Mar 22, 2012 · Viewed 30k times · Source

This is a sample pgm to check the functionality of Sleep() function.This is a demo only since iam using this sleep() and clock() functions in my app developement.

  // TestTicks.cpp : Defines the entry point for the console application.
  //

  #include "stdafx.h"
  #include<iostream>
  #include<iomanip>
  #include <Windows.h>

  int _tmain(int argc, _TCHAR* argv[])
  {
    int i, i2;
    i = clock();
    //std::cout<<" \nTime before Sleep() : "<<i;
    Sleep(30000);
    i2 = clock();
    //std::cout<<" \nTime After Sleep() : "<<i2;
    std::cout<<"\n Diff : "<<i2 -i;
    getchar();
      return 0;
  }

in this code i am calculating the time using clock() before and after the sleep function. Since iam using sleep(30000), the time diff would be atleast 30000.

I have run this prgm many times. and printed output as 30000, 30001, 30002. These are ok. But some times i am getting values like 29999 and 29997.How this possible, since i put 30000 sleep b/w the clock().

Please give me the reason for this.

Answer

SirDarius picture SirDarius · Mar 22, 2012

According to http://msdn.microsoft.com/en-us/library/windows/desktop/ms686298(v=vs.85).aspx:

The system clock "ticks" at a constant rate. If dwMilliseconds is less than the resolution of the system clock, the thread may sleep for less than the specified length of time. If dwMilliseconds is greater than one tick but less than two, the wait can be anywhere between one and two ticks, and so on.

It just means that the Sleep function will never sleep exactly for the amount of time given, but as close as possible given the resolution of the scheduler.

The same page gives you a method to increase the timer resolution if you really need it.

There are also high resolution timers that may better fit your needs.