JGerulskis
JGerulskis

Reputation: 808

Sleep() does not give accurate representation of time

I created a simple timer program as follows.

#include <conio.h>
#include <windows.h>
#include <iostream>
int main()
{
    float counter = 0;
    float time = 0;
    std::cin >> time;
    while (true){
        system("cls");
        std::cout << time - counter;
        Sleep(10);
        counter+= .01;
        if (time - counter < 0) break;
    }
}

As you can see instead of using Clock() I used Sleep(). When I have a less precise counter (Sleep(1000); counter += 1;) there's is not much, if any, variation from real time. However, the more precise I create the countdown the further from real time it becomes.

  1. Why is that so?
  2. Is there a work around if you know of one? Not a big deal though because Clock() works fine. This is mainly a curiosity driven question.

Upvotes: 0

Views: 61

Answers (2)

Paul Evans
Paul Evans

Reputation: 27577

It's because your system clock, which determines when to wake up your process, is being caught in between ticks.

Upvotes: 1

Ed Heal
Ed Heal

Reputation: 60007

Other things happen in the loop - and that takes time. Also sleep takes at least that period of time - but it can take more.

Use sleep but adjust the time by using the clock to take these factors into account.

Upvotes: 3

Related Questions