Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to port gethrtime() in C from Solaris to RHEL

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?

like image 836
SwapnilShivhare Avatar asked Jan 29 '23 12:01

SwapnilShivhare


2 Answers

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);
}
like image 62
dbush Avatar answered Feb 04 '23 11:02

dbush


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.

like image 27
Andrew Henle Avatar answered Feb 04 '23 09:02

Andrew Henle