Improved Hi-res timer

timespec diff(timespec start, timespec end)
{
    timespec temp;
    if ((end.tv_nsec-start.tv_nsec)<0) {
        temp.tv_sec = end.tv_sec-start.tv_sec-1;
        temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
    } else {
        temp.tv_sec = end.tv_sec-start.tv_sec;
        temp.tv_nsec = end.tv_nsec-start.tv_nsec;
    }
    return temp;
}

timespec t_start, t_end;

t_start.tv_nsec = 0;
t_start.tv_sec = 0;

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t_start);

// do stuff

clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &t_end);

wallClockDiff = diff(t_start, t_end);
double time = wallClockDiff.tv_sec + ((double)wallClockDiff.tv_nsec / 1000000000);

Hi-res timer

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

// ...

   gettimeofday(&tv, NULL);
   long t = tv.tv_sec*1000000 + tv.tv_usec;

// ... do your thing

   gettimeofday(&tv, NULL);
   t = 1000000*tv.tv_sec + tv.tv_usec - t;

Plain timer

#include <time.h>
                                                                                                             
int main(void)
{
   time_t  raw_time;
   raw_time = time(NULL);
   printf("time now is %s\n", ctime(&raw_time));
}

-- MattWalsh - 15 Jan 2005

Topic revision: r4 - 22 Apr 2010 - MattWalsh
 
This site is powered by the TWiki collaboration platformCopyright © 2008-2012 by the contributing authors. All material on this collaboration platform is the property of the contributing authors.
Ideas, requests, problems regarding TWiki? Send feedback