Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is Sleep() inaccurate?

I'm working on a timing system and I'll implement a timer class.

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

int main()
{
    clock_t t1, t2;
    t1 = clock();
    Sleep(10);
    t2 = clock();
    printf("%i\n", (int)(t2 - t1));
    return 0;
}

This program should print "10" but it prints "15" or "16". I need more accurate which is less than 1 ms! Suggestions? (maybe with select()'s timeout?)

NOTE: I've run this program on Windows 7 Ultimate x86. Program compiled with MinGW (C/C++) x86.

NOW I THINK >>

like image 543
PilawyerDev Avatar asked Feb 01 '26 00:02

PilawyerDev


1 Answers

Sleep() is accurate to the operating system's clock interrupt rate. Which by default on Windows ticks 64 times per second. Or once every 15.625 msec, as you found out.

You can increase that rate, call timeBeginPeriod(10). Use timeEndPeriod(10) when you're done. You are still subject to normal thread scheduling latencies so you still don't have a guarantee that your thread will resume running after 10 msec. And won't when the machine is heavily loaded. Using SetThreadPriority() to boost the priority, increasing the odds that it will.

like image 68
Hans Passant Avatar answered Feb 02 '26 14:02

Hans Passant



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!