UNIX Programming. struct timeval how to print it (C-programming)

In the GNU C Library, struct timeval:

is declared in sys/time.h and has the following members:

long int tv_sec

This represents the number of whole seconds of elapsed time.

long int tv_usec

This is the rest of the elapsed time (a fraction of a second), represented as the number of microseconds. It is always less than one million.

So you will need to do

printf("%ld.%06ld\n", usage.ru_stime.tv_sec, usage.ru_stime.tv_usec);

to get a "nicely formatted" timestamp like 1.000123.


Yes , timeval is defined like this

struct timeval { 
    time_t      tv_sec; 
    suseconds_t tv_usec; 
} 

Using

printf ("%ld.%06ld\n", usage.ru_stime.tv_sec, usage.ru_stime.tv_usec); 

will surely of help.


Since struct timeval will be declared something like:

struct timeval {
    time_t      tv_sec;
    suseconds_t tv_usec;
}

you need to get at the underlying fields:

printf ("%ld.%06ld\n", usage.ru_stime.tv_sec, usage.ru_stime.tv_usec);
printf ("%ld.%06ld\n", usage.ru_utime.tv_sec, usage.ru_utime.tv_usec);

yeah its

int main( void )
{
    clock_t start, stop;
    long int x;
    double duration;
    static struct timeval prev;
    struct timeval now;

    start = clock();  // get number of ticks before loop

    for( x = 0; x < 1000000000; x++ );
    // sleep(100);

    stop = clock();  // get number of ticks after loop

    // calculate time taken for loop
    duration = ( double ) ( stop - start ) / CLOCKS_PER_SEC;

    printf( "\nThe number of seconds for loop to run was %.2lf\n", duration );

    gettimeofday(&now, NULL);
    prev.tv_sec = duration;
    if (prev.tv_sec)
    {
        int diff = (now.tv_sec-prev.tv_sec)*1000+(now.tv_usec-prev.tv_usec)/1000;
        printf("DIFF %d\n",diff);
    }

    return 0;

}