Sample timestamp C
c, gcc, macos, timestamp
Solution
On OS X, you can use the `mach_absolute_time` function to get a high-precision timestamp:
#include <mach/mach_time.h>
#include <stdint.h>
/* get timer units */
mach_timebase_info_data_t info;
mach_timebase_info(&info);
/* get timer value */
uint64_t ts = mach_absolute_time();
/* convert to nanoseconds */
ts *= info.numer;
ts /= info.denom;
Note that if you are trying to time something, you should perform the final nanosecond conversion on the difference between timestamps (the duration) to avoid overflow problems.
Problem
I'm trying to understand what is the best way to sample timestamps in a Mac OS X 64 bit environment, using the gcc compiler. I read about the TSC register in x86 architectures and HPET for Intel processors, but I can't find a guide to use them. Actually, I tried with the function `gettimeofday()` but I need the precision of nanosecond. Can anyone lead me?