Reputation: 1803
I've got a small C program that makes use of difftime. its really strange, it doesn't print out the line after 10 seconds.
If however I uncomment out the sleep line then it works.
Any ideas why this is happening?
/* difftime example */
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, difftime, time, mktime */
int main ()
{
time_t start, stop;
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);
//sleep (1);
if (diff >= 10) {
printf("10 seconds passed...");
start = time(NULL);
}
}
}
BTW: Code compiles fine and I'm running it on the Raspberry Pi. 3.6.11+ #474 PREEMPT Thu Jun 13 17:14:42 BST 2013 armv6l GNU/Linux
Upvotes: 1
Views: 212
Reputation: 42165
Console IO might be line buffered. Try flushing
printf("10 seconds passed...");
fflush(stdout)
or adding a newline \n
printf("10 seconds passed...\n");
I can't reproduce any change in behaviour when the call to sleep
is uncommented.
Upvotes: 8
Reputation: 95512
For sleep(), you need to include unistd.h, as well as adding a newline as others have pointed out.
#include <stdio.h> /* printf */
#include <time.h> /* time_t, struct tm, difftime, time, mktime */
#include <unistd.h> /* sleep() */
If your code compiled without warnings and without including unistd.h, you need to crank your warnings up.
Upvotes: 0