4

I'm porting a C project from Solaris to Linux and recompiling it. In a logger.c, gethrtime() function of sys/time.h doesn't compile for Linux. How can I port it to Linux? Is there a substitute of this in Linux?

SwapnilShivhare
  • 105
  • 2
  • 5

3 Answers3

4

The function you're looking for is clock_gettime:

struct timespec t;
if (clock_gettime(CLOCK_MONOTONIC, &t) == -1) {
    perror("clock_gettime for CLOCK_MONOTONIC failed");
} else {
    printf("mono clock timestamp: %ld.%09ld\n", t.tv_sec, t.tv_nsec);
}

The CLOCK_MONOTONIC argument gets the time from an unspecified starting point. This differs from CLOCK_REALTIME which gets the wall clock time.

On most implementations the resolution will be in nanoseconds, however you can find the exact resolution by calling clock_getres:

struct timespec t;
if (clock_getres(CLOCK_MONOTONIC, &t) == -1) {
    perror("clock_getres for CLOCK_MONOTONIC failed");
} else {
    printf("mono clock resolution: %ld.%09ld\n", t.tv_sec, t.tv_nsec);
}
dbush
  • 205,898
  • 23
  • 218
  • 273
  • 1
    @SwapnilShivhare The `clock_getres` function tells you the resolution the real time clock, not the timer itself. The output is telling you that one tick is 1 ns. You need to call `clock_gettime` to get the time. – dbush Mar 15 '18 at 18:47
3

This is what I've had around for 10+ years:

Header file:

#ifdef __linux
typedef uint64_t hrtime_t;
hrtime_t gethrtime( void );
#endif

Source code:

#ifdef __linux

hrtime_t gethrtime( void )
{
    struct timespec ts;
    hrtime_t result;

#ifdef CLOCK_MONOTONIC_HR
    clock_gettime( CLOCK_MONOTONIC_HR, &ts );
#else
    clock_gettime( CLOCK_MONOTONIC, &ts );
#endif

    result = 1000000000LL * ( hrtime_t ) ts.tv_sec;
    result += ts.tv_nsec;

    return( result );
}

#endif

It probably should have some error checking, but since gethrtime() doesn't have any way to return an error, I didn't see any reason to add it here.

Andrew Henle
  • 32,625
  • 3
  • 24
  • 56
1

Read time(7). You probably want to use clock_gettime(2).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547