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;
}
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.
int, it's that the test is happening several times a second. So, if this code actually ran for more than a minute (which I very much doubt), every time it hit a minute mark (including 0), it would spit out the message several times - jpm 2012-04-04 17:09
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 windowsdiff > 0 && diff % 60 == 0 doesn't help you, than I don't know answer to this problem;/ - Jarosław Gomułka 2012-04-04 17:17