[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: gettimeofday() and clock



On Sun, 25 Aug 2002, Francesco Orsenigo wrote:

> 
> I wrote some timer code using gettimeofday(), as it seems to me the only 
> linux `standard` way to obtain non-blocking subsecond precision.
> 
> However i find that the tv_usec field increases by 10000 per second instead 
> of 1000.
> May this depend on the CPU? (k7 850Mhz)
> Is possible to know the number of usecs ('u' stands for `micro`?) per second 
> without calling other timing functions?
> Is possible to get subsecond precision with other non-blocking functions?
> 
> I've put the test program here:
> http://freeweb.lombardiacom.it/xarvh/timer.c

Let me start by saying that it is late, and your program confuses me a
lot. start does not seem to be initialised. You have a modulo and two
divisions where a single division - perhaps two - ougth to be enough. It
is like it the program is trying to do two things at once.

So, here is a version that, to me, is clearer:

#include <sys/time.h>
#include <time.h>
#include <unistd.h>
#include <stdio.h>

static struct timeval start[1];
static struct timeval now[1];

int main() {
  unsigned long t;
  gettimeofday(now, 0);
  while(1) {
    start[0] = now[0];
    /* Note, sleep is not accurate at all. */
    sleep(1);
    gettimeofday(now, 0);
    t = (now->tv_sec - start->tv_sec)*1000000 
      + (now->tv_usec - start->tv_usec);  
    printf("usecs: %ld\n", t);
    printf("Ticks: %ld\n", t/50000);
  }
}

It outputs stuff like this:

usecs: 1004588
Ticks: 20
usecs: 1010077
Ticks: 20
usecs: 1009948
Ticks: 20
usecs: 1010086
Ticks: 20
usecs: 1009871
Ticks: 20
usecs: 1010019
Ticks: 20
usecs: 1009980
Ticks: 20
usecs: 1010288
Ticks: 20
usecs: 1009770
Ticks: 20

Which is to be expected.
 
The slight overhead is slightly CPU dependant, but please not that you 
should expect 10 ms to pass when you sleep.

Check the man page for sleep and nanosleep.

Mads

-- 
Mads Bondo Dydensborg.                               madsdyd@challenge.dk
The Microsoft Dictionary:

           interoperability: The ability of a Microsoft product to operate
                             with another Microsoft product.