My try. (Almost) perfectly POSIX. Works on both POSIX and MSVC/Win32 also.
#include <stdio.h>
#include <time.h>
const int NUM_SECONDS = 10;
int main()
{
int count = 1;
double time_counter = 0;
clock_t this_time = clock();
clock_t last_time = this_time;
printf("Gran = %ld
", NUM_SECONDS * CLOCKS_PER_SEC);
while(true)
{
this_time = clock();
time_counter += (double)(this_time - last_time);
last_time = this_time;
if(time_counter > (double)(NUM_SECONDS * CLOCKS_PER_SEC))
{
time_counter -= (double)(NUM_SECONDS * CLOCKS_PER_SEC);
printf("%d
", count);
count++;
}
printf("DebugTime = %f
", time_counter);
}
return 0;
}
This way you can also have the control on each iteration, unlike the sleep()-based approach.
This solution (or the same based on high-precision timer) also ensures that there is no error accumulation in timing.
EDIT: OSX stuff, if all else fails
#include <unistd.h>
#include <stdio.h>
const int NUM_SECONDS = 10;
int main()
{
int i;
int count = 1;
for(;;)
{
// delay for 10 seconds
for(i = 0 ; i < NUM_SECONDS ; i++) { usleep(1000 * 1000); }
// print
printf("%d
", count++);
}
return 0;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…