I am trying to write a helper method in iOS to allow me to use mach_absolute_time()
into seconds (or nanoseconds), so that I can find the time derivative of incoming device sensor data. Here is my attempt:
#include <mach/mach_time.h>
- (double) convertMachAbsoluteTimeIntoSeconds:(uint64_t) mach_time {
mach_timebase_info_data_t _clock_timebase;
double nanos = (mach_time * _clock_timebase.numer) / _clock_timebase.denom;
return nanos / 1e9;
}
The above code is compiling but the current warning I am getting is that the 'right operand of '*' is a garbage value'. Plus, it isn't returning a sensible result in any case :/
From what I've read, mach_absolute_time()
has some idiosyncrasies, so I figured that getting this working might be useful to others.
All help graciously received!
You've declared _clock_timebase
, but you never initialized it so it's just filled with garbage values on the stack. You meant the following:
mach_timebase_info_data_t _clock_timebase;
mach_timebase_info(&_clock_timebase); // Initialize timebase_info
...
You may find it more convenient to use AbsoluteToNanoseconds
to do this for you. For full examples, see QA1398: Mach Absolute Time Units.
Note that mach_timebase_info is promised to be stable, so you can initialize this a single time if you like. (If it weren't stable, it'd be impossible to avoid race conditions on checking it with the existing API, so good thing there....)