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?
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With