Re: timer with C



On a sunny day (Sun, 26 Mar 2006 11:31:36 +0200) it happened "Manu"
<info@xxxxxxxx> wrote in <44265f05$0$20141$8fcfb975@xxxxxxxxxxxxxxx>:

Hi,

I want to launch a function or a procedure every 100 ms, in an console mode
application

Is there any howto for this?
Dunno about howto.
But here is something to think about.

When the kernel task switch comes, it wil lleave your app as is,
and it is not guaranteed to always be back in time for your check
of the 100 mS:



// vars
unsigned long lstart_usecs, lcurrent_usecs, ldiff_usecs;
struct timeval *start_timeval;
struct timeval *current_timeval;

// init
start_timeval = malloc(sizeof(struct timeval) );
if(!start_timeval)
{
fprintf(stderr, "mcamip: could not allocate space for start_timeval, aborting.\n");

exit(1);
}

current_timeval = malloc(sizeof(struct timeval) );
if(!current_timeval)
{
fprintf(stderr, "mcamip: could not allocate space for current_timeval, aborting.\n");

exit(1);
}


// your loop
while(1)
{
/* get elapsed time */
gettimeofday(current_timeval, NULL);

/* calculate time since previous picture */
lcurrent_usecs =\
current_timeval -> tv_usec + (1000000 * current_timeval -> tv_sec);

lstart_usecs =\
start_timeval -> tv_usec + (1000000 * start_timeval -> tv_sec);

ldiff_usecs = lcurrent_usecs - lstart_usecs;

// NOW your test
if(ldiff_usecs >= 100000)
{
fprintf(stderr, "Time is up dude!\n");
}

} // end while


It will ON AVERAGE generate a print statement every 100mS, but sometimes
it will be late by the time the kernel took to do other things with other
pids.


.