Jump to content

[SOLVED] Accuracy of sleep() function


photo

Recommended Posts

I have a count-down timer which is running in a thread updating a label. 

forloop(int i = 0; pre_secs + 1 ) {
    label_right.setText(format("%02d:%02d",mins,secs));
    sleep(1.0f);

    secs--;
    if (secs == -1) {
        secs = 0;
        mins--;
    }
}

I am noticing that the time counts down too quickly. The 'sleep()' function does not appear to be 100% accurate. Is that correct? Is there a better way of pausing for a second?

 

There are no other threads executing. This thread is spawned by init() and is the main loop of the application. I'm running on Windows 7 pro 64 bit using the last-but-one SDK and the "launch_release.bat" to execute 

Link to comment

Hi Angus,

 

Unfortunately, due to floating point calculations errors you can't measure time intervals strictly and you always will get different values from sleep(1.0f) function (0.9831, 1.0134, etc).

 

Please, check this sample code. It shows how to calculate seconds and minutes more precisely.

How to submit a good bug report
---
FTP server for test scenes and user uploads:

Link to comment

Hi Angus,

 

Unfortunately, due to floating point calculations errors you can't measure time intervals strictly and you always will get different values from sleep(1.0f) function (0.9831, 1.0134, etc).

 

Please, check this sample code. It shows how to calculate seconds and minutes more precisely.

 

 

Ok - but I'm consistently getting something like 0.70 - but only when the process has been running for a few hours. I can understand a few millis either way, but 0.3 out on a 1.0 call is pretty poor. 

 

I'll work around it for now, but I regard this as a bug. Can it go in to the bug tracker?

 

 

Edit: an accurate sleep() function;

/*
 * The sleep() function is inacccurate and so we must "busy wait"
 * in order to get precision
 */

void mysleep(float howlong) {

  float now = clock();
  float then = now + howlong;



  while (1) {
    wait;
    if (clock() >= then) {
      return;
    }
  }
}

Link to comment

Hi Angus,

 

There is indeed an issue with sleep() function in combination with long time running process. Recommended way to calculate minutes and seconds you can find in this code snippet. This code can work for hours without such precision errors.

 

I will pass information about sleep() fuction behavior to the developers.

 

Thanks!

  • Like 1

How to submit a good bug report
---
FTP server for test scenes and user uploads:

Link to comment

> I will pass information about sleep() fuction behavior to the developers.

 

Thanks, Silent. Much appreciated. 

 

Perhaps it would be a good idea to be open about current issues in Unigine so us as customers can know that we need work-arounds before we spend time debugging and posting queries on this forum. 

Link to comment
×
×
  • Create New...