IOS get time in Nanoseconds Or Milliseconds

Spread the love

To get the time in nano seconds or milli seconds use the following code snippet:

      mach_timebase_info_data_t sTimebaseInfo;
      uint64_t machTime = mach_absolute_time();

      // Convert to milliseconds
      mach_timebase_info(&sTimebaseInfo);
      machTime *= sTimebaseInfo.numer;
      machTime /= sTimebaseInfo.denom;
      machTime /= 1000000; // convert from nanoseconds to milliseconds
      return machTime;

For more on this look into the IOS docs: mach_absolute_time | Apple Developer Documentation

There is another method now, which we can use directly and make it more concise:

clock_gettime_nsec_np(CLOCK_UPTIME_RAW) 

For more details of the IOS version support check the chromium usage of this function:

https://chromium.googlesource.com/external/github.com/abseil/abseil-cpp/+/refs/heads/lts_2018_06_20/absl/time/internal/get_current_time_ios.inc

There is another method:

double CurrentTime = CACurrentMediaTime();

But from the docs it looks like it will only return the time in seconds: CACurrentMediaTime() | Apple Developer Documentation

You will also use ‘NSDate’. But it will take the system time into consideration and if it syncs in between then time will jump: timeIntervalSince1970 | Apple Developer Documentation

Cheers and Peace out!!!