Blog Archive

Monday, June 11, 2018

How to use struct timeval and gettimeofday to get the execution time?

c - How to use struct timeval to get the execution time? - Stack Overflow:



https://stackoverflow.com/questions/12722904/how-to-use-struct-timeval-to-get-the-execution-time

[Abstract] 

struct timeeval
gettimeofday

[Background]

timeval {
        long    tv_sec;        /* seconds */ //long= long int
        long    tv_usec;       /* and microseconds */
};




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

int main (int argc, char** argv) {
    struct timeval tvalBefore, tvalAfter;  // removed comma

    gettimeofday (&tvalBefore, NULL);
    int i =0;
    while ( i < 10000) {
        i ++;
    }

    gettimeofday (&tvalAfter, NULL);

    // Changed format to long int (%ld), changed time calculation

    printf("Time in microseconds: %ld microseconds\n",
            ((tvalAfter.tv_sec - tvalBefore.tv_sec)*1000000L
           +tvalAfter.tv_usec) - tvalBefore.tv_usec
          ); // Added semicolon
    return 0;
}
'via Blog this'

No comments:

Post a Comment