3

I am interested in accurately timing a c++ application. There seems to be multiple definitions for "time", but for the sake of this question... I am interested in the time that I am counting on my watch in the real world... if that makes any sense! Anyway, in my application, my start time is done like this:

clock_t start = clock();
.
.
. // some statements
.
.
clock_t end = clock();
.
.
double duration = end - start;
.
.
cout << CLOCKS_PER_SEC << endl;

start is equal to 184000 end is equal to 188000 CLOCKS_PER_SEC is equal to 1000000

Does this mean the duration (in seconds) is equal to 4000/1000000 ? If so, this would mean the duration is .004 seconds? Is there a more accurate way of measuring this?

Thank you

code
  • 5,294
  • 16
  • 62
  • 113
  • i think you are looking for [milliseconds in c++][1] [1]: http://stackoverflow.com/questions/15235218/c-timer-milliseconds – garakchy Mar 05 '14 at 01:50
  • 1
    hi garakchy. How can I capture the milliseconds here? – code Mar 05 '14 at 02:06
  • 1
    Is it true that milliseconds is equal to = diffticks / ( CLOCKS_PER_SEC / 1000 ); ? – code Mar 05 '14 at 02:06
  • 1
    Ah yes.. if I do my math correctly... Clocks x (1000 milliseconds / clocks per second) is equal to milliseconds – code Mar 05 '14 at 02:18
  • A small way to improve accuracy is the when calling `clock()`, code is _someplace_ within 0.0 to 1.0 clock ticks. By doing `clock_t start,t; t = clock(); while ((start = clock()) == t);` will reduce the variation on the start time. Not much help on the `end` call though. – chux - Reinstate Monica Mar 05 '14 at 05:08
  • `(CLOCKS_PER_SEC / 1000 )` is bad. Say `CLOCKS_PER_SEC` was 999, then `(CLOCKS_PER_SEC / 1000 )` is 0. Better `(diffticks * 1000 + CLOCKS_PER_SEC/2)/ CLOCKS_PER_SEC`, but then watch out for overflow. – chux - Reinstate Monica Mar 05 '14 at 05:11

1 Answers1

1

Try this to find the time in nanoseconds precision

struct timespec start, end;
clock_gettime(CLOCK_REALTIME,&start);
/* Do something */
clock_gettime(CLOCK_REALTIME,&end);

It returns a value as ((((unsigned64)start.tv_sec) * ((unsigned64)(1000000000L))) + ((unsigned64)(start.tv_nsec))))

If you find this helpful kindly refer this link too..

Community
  • 1
  • 1
Siva
  • 141
  • 1
  • 2
  • 12