High-resolution timers rely on the fact that modern processors have a clock rate of at least one billion cycles per second. An implementation can use the ticks of the system's processor (or a dedicated processor used exclusively for time measurement) to create a timer with a nanosecond granularity.
The real-time POSIX standard defines the gethrtime() function which offers a nanosecond granularity, at least in theory. Solaris, AIX, real-time variants of Linux and several other POSIX implementations already support this function:
returns the value of a high resolution timer that started counting time since some arbitrary time in the past (typically, the timer starts measuring time since the most recent system booting). gethrtime()
reports the time as the number of nanoseconds elapsed since that arbitrary moment in the past. The typedef hrtime_t
is a 64-bit signed integer. The high-resolution timer used by gethrtime()
is not correlated in any way to the time of day; therefore it's not subject to resetting or being manipulated by adjtime()
The constant HRTIME_INFINITY represents the maximum possible value that gethrtime() could return. The HRTIME_INFINITY value will never be reached during the execution of the current process. Therefore, you can use this constant to designate the infinitely distant moment in time.
Although the return value of gethrtime() is expressed as nanoseconds, the actual granularity is hardware-dependent and may be coarser than that. If two consecutive calls to gethrtime() take place very proximately, you could still get identical results on certain hardware architectures. However, there are some guarantees:
- Monotonicity. The later of two consecutive gethrtime() calls will not decrease. In addition, the result of gethrtime() will not roll over.
- Linearity. These functions won't speed up or slow down; they are independent of system load and other performance issues that may affect time(), clock(), or gettimeofday().
The cost of calling gethrtime()
is low: three CPU cycles or even less. As such, frequent gethrtime()
calls during profiling or testing have minimal effect on the performance of the process being profiled.
The following code listing measures the average time in nanoseconds needed for executing a getpid() call using gethrtime():
hrtime_t start, end;
start = gethrtime();
for (int n = 0; n < 10; n++)
end = gethrtime();
printf("%lld nsec\n on average", (end - start) / 10);