Reputation: 808
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.
Clock()
works fine. This is mainly a curiosity driven question.Upvotes: 0
Views: 61
Reputation: 27577
It's because your system clock, which determines when to wake up your process, is being caught in between ticks.
Upvotes: 1
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