I am trying to read time to 1/100th of a sec. in Linux using C.
Most of the time functions (from the man) are good to a sec.
The gettimeofday() promises to tell time down to microseconds.
That is better than what I wanted.

I tried the following progam to test my understanding of struct.
It seems to work if I just declare one pair struct variable the way
it is in the program. If I declace two pairs struct variables say
like this

    struct timeval *t1;
    struct timezone *z1;
    struct timeval *t2;
    struct timezone *z2;

the first two will work, while the second pair won't. If I didn't
declare the struct and just use the variable tv as stated in the man
page, the program works also. But if I can use two differently names
variables when calling the gettimeofday function, the program will
look nicer IMHO. If someone can explain this I'll be most grateful.

Lastly this program works if I compile without -O option but just
give a very large negative numbers if compiled with -O. Why?

Regards.

Khalid


PS. On Pentium 166Mhz the loop in the prog. took roughly 23000 usec.
    How fast is it on PII? I am considering on getting one but would
    like to know how much improvement I can get before deciding on it.


The program follows:

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

int main(){
    struct timeval *t1;
    struct timezone *z1;
    int k;
    long sec_start, usec_start, sec_stop, usec_stop;
    double w;

    gettimeofday(t1, z1);
    sec_start = t1->tv_sec;
    usec_start = t1->tv_usec;
    printf("start: sec = %d  usec = %d\n", t1->tv_sec, t1->tv_usec);

    for(k=1; k<=20000; k++)
       w = tan(k);

    gettimeofday(t1, z1);
    sec_stop = t1->tv_sec;
    usec_stop = t1->tv_usec;

    printf("stop : sec = %d  usec = %d\n",
           t1->tv_sec, t1->tv_usec);
    printf("diff : sec = %d  usec = %d\n",
           sec_stop-sec_start, usec_stop-usec_start);

    return 0;
}

Reply via email to