Reputation: 419
I am trying to create a loop function based on the time. After the iteration, it will print every 60 second "60 second passed". But this code result me in couple of "60 second passed" while actually me watch does not even showing 1 minute already.. I tried below, but I am expecting it to show me this information, but it does not (only the first couple of lines of iteration. afterwards not..)
Can anyone help in this matter? Thank you
#include <stdio.h>
#include <time.h>
int main()
{
time_t start,stop;
start = time(NULL);
time(&start);
int iteration, i;
for (iteration = 1; iteration <= 500; iteration++) {
for (i = 0; i <= 50; i++) {
printf("looping while waiting 60 second..\n");
}
stop = time(NULL);
int diff = difftime(start, stop);
if (diff % 60 == 0) {
printf("60 second passed..");}
}
return 1;
}
Upvotes: 1
Views: 2088
Reputation: 3155
difftime
and the following code are likely being executed multiple times before even one second has passed. As a result, difftime
will return a value < 1, which is truncated to 0 by your implicit cast. And of course 0 % 60 == 0
.
EDIT:
You might consider something like:
start = time(NULL);
for(; /* some condition that takes forever to meet */;) {
// do stuff that apparently takes forever.
stop = time(NULL);
double diff = difftime(stop, start);
if (diff >= 60) {
printf("60 seconds passed...");
start = time(NULL);
}
}
Also note that in your example code, start
and stop
should be flipped in the call to difftime
.
Upvotes: 3
Reputation: 4995
It is very likely that difftime is equal to 0. If you want to wait for 60 seconds you should consider using functions:
usleep
on linuxsleep
on windowsUpvotes: 2