0

I am trying to do a timer in microseconds, but it's not quite working.

#include <time.h>
#include <iostream>
#include <unistd.h>

using namespace std;

int main ()
{
    struct timespec start_time;
    struct timespec end_time;
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start_time);
    usleep(5000);
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end_time);
    cout << "START: " << (start_time.tv_nsec/1000) << endl;
    cout << "END: " << (end_time.tv_nsec/1000) << endl;
    cout << "DIFF: " << (end_time.tv_nsec - start_time.tv_nsec) /1000 << endl;

    return 0;
}

The result look like this:

START: 3586
END: 3630
DIFF: 43

I need the DIFF be around 5000. Any suggestions?

3 Answers3

1

I'm not sure what you're trying to measure, but I guess CLOCK_PROCESS_CPUTIME_ID is the wrong timer, you likely want CLOCK_MONOTONIC if you want to measure some elapsed time. Have a look at a similar stackoverflow question that shows the difference between the different clocks of clock_gettime.

That said, to get the full time you have to add tv_sec and tv_nsec (of course first converting tv_sec to nano seconds) of each measurement and then subtract that total, so something like:

uint64_t startNs = start_time.tv_sec * 1000 * 1000 * 1000 + start_time.tv_nsec;
uint64_t endNs = end_time.tv_sec * 1000 * 1000 * 1000 + end_time.tv_nsec;
uint64_t diffNs = endNs - startNs;
uint64_t diffMicro = diffNs / 1000;

And if you're on C++11, probably best use some high level class from the chrono namespace.

Community
  • 1
  • 1
Janick Bernet
  • 20,544
  • 2
  • 29
  • 55
  • I think that you may be in the realms of overflow. That is the reason why the structure has two parts – Ed Heal Apr 20 '14 at 19:27
1

Two things.

  1. Guess you need CLOCK_REALTIME
  2. There are two components of timespec - need to take both into account when doing the subtraction
Ed Heal
  • 59,252
  • 17
  • 87
  • 127
1

try with clock_gettime( CLOCK_REALTIME, &start) clock_gettime( CLOCK_REALTIME, &stop)

You need to use 'tv_sec' part of the timespec structure as well.

Time = ((stop.tv_sec - start.tv_sec)+ (double)(stop.tv_nsec - start.tv_nsec)/1e9)*1000;//im ms

nittoor
  • 113
  • 6