Page 1 of 1

msleep

Posted: Wed Feb 19, 2020 11:30 pm
by Rebel
Can a PC really measure 1/1000 of a second?

Code: Select all

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void main()
{       int x;
        printf("start : %d\n",clock());
        for (x=0; x<100; x++) msleep(1);
        printf("end   : %d\n",clock());
}
msleep(1) gives 1.560
msleep(10) also gives 1.560
msleep(15) also gives 1.560

msleep(16) gives 3.120
msleep(20) also gives 3.120

Re: msleep

Posted: Thu Feb 20, 2020 12:11 am
by Dann Corbit
I cannot see the body of msleep().

The resolution of the clock() function is described by the macro:
CLOCKS_PER_SEC
See, for example:
https://www.gnu.org/software/libc/manua ... -Time.html

There are other timers for Windows. There is (for instance) a high resolution timer you can use.
https://docs.microsoft.com/en-us/window ... ime-stamps

Re: msleep

Posted: Thu Feb 20, 2020 2:42 am
by bob
Easy thing to explain:

"windows is NOT the answer. Windows? is the question. NO is the answer -- Linus Torvalds... :)

Re: msleep

Posted: Thu Feb 20, 2020 1:29 pm
by hgm
The problem might be in clock(), which just reads the rather slowly ticking time-of-day clock of your PC. You cannot use clock() to check if msleep() is OK.

Note that CLOCKS_PER_SEC is not the final answer; I have seen Linux systems where it was 1000 (or was it a million), but the increments were far greater than one. So it only describes the units used by the return value of clock(), not how frequently it actually ticks. In other words, it specifies precision rather than accuracy.

On Windows you can use GetTickCount() to get a time with msec accuracy.

Re: msleep

Posted: Thu Feb 20, 2020 3:40 pm
by Joost Buijs
If you want to have sub microsecond accuracy on Windows you can use QueryPerformanceFrequency() and QueryPerformanceCounter().

Re: msleep

Posted: Thu Feb 20, 2020 4:44 pm
by jstanback
Here's what I use in Wasp for both Windows and Linux. Reset != 0 starts the timer and reset == 0 returns the elapsed time in seconds (floating point). I think its accurate to well under a millisecond.

John

Code: Select all

void GetElapsedTime(int reset)
{
  struct timespec ts;
  static double start = 0.0;
  if (reset)
    {
      clock_gettime(CLOCK_MONOTONIC,&ts);
      start = (double)ts.tv_sec + 1.0e-9*ts.tv_nsec;
      SD->elapsed_time = 0.0;
    }
  else
    {
      clock_gettime(CLOCK_MONOTONIC,&ts);
      SD->elapsed_time = (double)ts.tv_sec + 1.0e-9*ts.tv_nsec - start;
    }
}

Re: msleep

Posted: Thu Feb 20, 2020 5:16 pm
by Joost Buijs
In the latest version of my engine I also use the chrono lib.

I measure duration like this:

Code: Select all

			auto t0 = high_resolution_clock::now();
			// do something in between
			auto t1 = high_resolution_clock::now();
			auto delta_t = duration_cast<duration<double>>(t1 - t0).count();
However I never measured what the resolution is.