Thursday 6 November 2014

Measuring system time with micro second precision in c++

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

struct timeval start, end;
long mtime, secs, usecs;

int main(int argc, char * argv[]){

gettimeofday(&start, NULL);

sleep(10);

gettimeofday(&end, NULL);
secs  = end.tv_sec  - start.tv_sec;
usecs = end.tv_usec - start.tv_usec;
mtime = ((secs) *1000* 1000 + usecs) ;
printf("Elapsed time: %ld usecs\n", mtime);
        return 0;
}


OUTPUT:
-------------
> ./a.out
Elapsed time: 10,003,866 usecs

1 comment: