I am trying to increase the value of variable t by one per 10ms for 60s. Ideally, the value of t should be closed to 6000. I attempted to do it through a simple while loop below. However, the printed value of t was only 2996. Could it because of the overhead of running usleep? Or, I am not getting and using the time values properly? Any comment or suggestion is appreciated, thanks!
I am doing it on a Solaris 10 box.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main(int argc, char *argv[])
{
long t = 0;
int duration = 60;
time_t currentTime = time(NULL);
time_t targetEndTime = currentTime + duration;
while(currentTime < targetEndTime){
//pause for 10ms
usleep(10000);
currentTime = time(NULL);
t++;
}
printf("t = %d\n", t);
}
POSIX semantics for usleep (as with all "sleep" type functions) makes only the guarantee
that your program will sleep for at least the specified time. It could sleep for any
amount of time, even infinity.
C++ itself does not have any sleep functions at all, usleep etc. is provided by your operating system.
What you can do is to check how much time has passed after the usleep call returns and sleep less in the next iteration if necessary.