Sleep(100) takes 94 ms or 110 ms

 

Hi everyone,

using Sleep(100) in a loop does not take 100 milliseconds.

  while(!IsStopped())
  {
  int GlobalTicker = GetTickCount();
  Sleep(100);
  Print("loop duration after sleep: ",GetTickCount()-GlobalTicker);
  

I get values above or below:

The problem gets even bigger using shorter sleep durations. Using Sleep(1) leeds to a sleep time of 0 ms or 16 ms.

Has someone an idea how to solve this?

Kind regards,

Jan.

 
int OnInit()
{
  EventSetMillisecondTimer(25);
  return(INIT_SUCCEEDED);
}

int prevGTC= GetTickCount();
void OnTimer()
{
  Print("loop duration after sleep: ",GetTickCount()-prevGTC);
  prevGTC= GetTickCount();
} 

Using OnTimer() brings a better result (more stable) but still not very stable:


 
Jan Tarnogrocki:

Using OnTimer() brings a better result (more stable) but still not very stable:


The Sleep works fine, but you are using GetTickCount for your metrics. It has resolution of 15-16 ms.
 
Ovo Cz:
The Sleep works fine, but you are using GetTickCount for your metrics. It has resolution of 15-16 ms.
How to measure it another way than using GetTickCount()?
 
int loopcnt;

int OnInit()
{
   uint prevGTC=0;
   while(!IsStopped())
   {
      loopcnt++;
      if(loopcnt>=100)
      {
       double var = (GetTickCount()-prevGTC)/loopcnt;
       Print("loop duration after sleep: ",var);
       prevGTC= GetTickCount();
       loopcnt=0;
      }
    Sleep(1);      
   }
   
 return(INIT_SUCCEEDED);
}
OK, this shows an average loop duration of 1 ms. But this is no evidence that every single loop takes 1 ms.
 
#import "Winmm.dll"
 int timeGetTime();
#import

int OnInit()
{
   uint prevGTC=0;
   while(!IsStopped())
   {
      int a  = timeGetTime();
      Sleep(5);        
      Print(timeGetTime()-a);
   }
 return(INIT_SUCCEEDED);
}

At least accurate to 1ms with my PC.

 
You may use microseconds.
 
Stanislav Korotky:
You may use microseconds.

Thanks, that´s great!

Although it seems that it returns nanoseconds and not microseconds. Need to divide the result by 1000 to get microseconds.

int OnInit()
{
   while(!IsStopped())
   {
      int prevGMSC  = GetMicrosecondCount();
      Sleep(10);        
      Print(DoubleToStr((GetMicrosecondCount()-prevGMSC)/1000,0));
   }
 return(INIT_SUCCEEDED);
}
 
Jan Tarnogrocki:

Thanks, that´s great!

Although it seems that it returns nanoseconds and not microseconds. Need to divide the result by 1000 to get microseconds.

You divide by 1000 to get milliseconds. There is no problem.
Reason: