Sleep() function usage

30,143

Solution 1

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.

Solution 2

Unless you're using a realtime OS, that is very much expected.

The Operating System has to schedule and run many other processes, so waking yours' up may not match the exact time you wanted to sleep.

Solution 3

The clock() function tells how much processor time the calling process has used.

You may replace the use of clock() by the function GetSystemTimeAsFileTime in order to measure the time more accurately.

Also you may try to use timeBeginPeriod with wPeriodMin returned by a call to timeGetDevCaps in order to obtail maximum interrupt frequency.

In order to synchronize the sleeps with the system interrupt period, I'd also suggest to have a sleep(1) ahead of the first "time capture".

By doing so, the "too shorts" will disappear.

More information abount sleep can be found here

Share:
30,143
Aneesh Narayanan
Author by

Aneesh Narayanan

Updated on February 13, 2020

Comments

  • Aneesh Narayanan
    Aneesh Narayanan over 4 years

    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.