After going through this thread, I understand that clock_gettime() and clock_getres() are an option to implement QueryPerformanceCounter & QueryPerformanceFrequency in Linux environments.
Many examples suggest reading out value returned by clock_gettime and using it. But that will just be number of nanoseconds and not the number of ticks! So the only way to get number of ticks in Linux is to use a combination of clock_gettime() & clock_getres(). Please correct me if I am wrong.
So I implemented my QueryPerformanceCounter (and it seems very ugly!) So wanted to know if there are better ways to implement QueryPerformanceCounter for Linux. My code is below -
__int64 QueryPerformanceCounter()
{
__int64 nsec_count, nsec_per_tick;
/*
* clock_gettime() returns the number of secs. We translate that to number of nanosecs.
* clock_getres() returns number of seconds per tick. We translate that to number of nanosecs per tick.
* Number of nanosecs divided by number of nanosecs per tick - will give the number of ticks.
*/
struct timespec ts1, ts2;
if (clock_gettime(CLOCK_MONOTONIC, &ts1) != 0) {
printf("clock_gettime() failed");
return -1;
}
nsec_count = ts1.tv_nsec + ts1.tv_sec * nsec_per_sec;
if (clock_getres(CLOCK_MONOTONIC, &ts2) != 0) {
LOG_ERROR("clock_getres() failed");
return -1;
}
nsec_per_tick = ts2.tv_nsec + ts2.tv_sec * nsec_per_sec;
return (nsec_count / nsec_per_tick);
}
Thanks!