Fix: Getting Precise Millisecond Timing in iOS and macOS with Swift and Objective-C

Fix: Getting Precise Millisecond Timing in iOS and macOS with Swift and Objective-C

Written by

in

Quick answer: Use CACurrentMediaTime() for UI-related timing and clock_gettime(CLOCK_MONOTONIC_RAW) or Swift’s ContinuousClock for general high-resolution measurements. Avoid NSDate for sub-millisecond work — it only provides millisecond precision at best.

Why this happens

Accurate timing is essential for measuring scroll velocity, animation performance, audio latency, and benchmarking critical code paths. The original NSDate API returns an NSTimeInterval (a Double representing seconds) but its practical resolution is limited to roughly a millisecond on modern hardware. For scroll-speed calculations or frame-time analysis you need microsecond or nanosecond granularity.

Apple has introduced several monotonic clocks over the years. mach_absolute_time() was the first high-resolution option, but it returns raw CPU ticks that require conversion with mach_timebase_info. CACurrentMediaTime() wraps the same clock in seconds as a CFTimeInterval, making it convenient for Core Animation work. Modern POSIX clock_gettime() with CLOCK_MONOTONIC_RAW gives direct nanosecond access without conversion. Swift 5.7 added ContinuousClock and Instant for a type-safe, platform-agnostic API.

Choosing the wrong clock — or worse, a wall-clock like Date() — introduces drift from NTP adjustments, sleep/wake cycles, and timezone changes. Monotonic clocks guarantee time only moves forward at a steady rate.

How to fix it

1. Swift: Use ContinuousClock (iOS 16+, macOS 13+)

ContinuousClock is the modern, Swifty way to measure elapsed time with nanosecond precision. It automatically selects the best underlying monotonic clock.

import Foundation

let clock = ContinuousClock()
let start = clock.now

// … code to measure …

let elapsed = clock.now - start
print("Elapsed: \(elapsed.formatted(.units(allowed: [.seconds, .milliseconds, .microseconds, .nanoseconds]))) )
// Example: Elapsed: 1.234567 ms

Instant conforms to Comparable and Hashable, so you can store start points in collections. The Duration type provides type-safe arithmetic and formatting.

2. Swift / Objective-C: CACurrentMediaTime() for UI and animation work

When your timing relates to Core Animation, CADisplayLink, or scroll-view callbacks, CACurrentMediaTime() is the canonical choice. It returns seconds as a Double (CFTimeInterval) with sub-microsecond resolution and is already in the same time base as the render server.

import QuartzCore

let start = CACurrentMediaTime()
// … scroll or animation work …
let elapsedMs = (CACurrentMediaTime() - start) * 1000
print("Scroll delta: \(elapsedMs) ms")
#import <QuartzCore/QuartzCore.h>

CFTimeInterval start = CACurrentMediaTime();
// … work …
double elapsedMs = (CACurrentMediaTime() - start) * 1000.0;
NSLog(@"Elapsed: %f ms", elapsedMs);

No linking step beyond QuartzCore.framework is required.

3. Cross-platform C / Objective-C: clock_gettime(CLOCK_MONOTONIC_RAW)

For the highest resolution without Swift overhead, call POSIX clock_gettime directly. CLOCK_MONOTONIC_RAW is not subject to NTP slew corrections, unlike CLOCK_MONOTONIC.

#include <time.h>
#include <stdint.h>

uint64_t now_ns(void) {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
    return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;
}

// Usage
uint64_t start = now_ns();
// … work …
uint64_t elapsed_ns = now_ns() - start;
double elapsed_ms = elapsed_ns / 1_000_000.0;

In Objective-C you can wrap this in a small helper class:

// MonotonicTimer.h
#import <Foundation/Foundation.h>

@interface MonotonicTimer : NSObject
+ (instancetype)start;
- (double)elapsedMilliseconds;
@end

// MonotonicTimer.m
#import "MonotonicTimer.h"
#include <time.h>

@implementation MonotonicTimer {
    uint64_t _startNs;
}

+ (instancetype)start {
    MonotonicTimer *t = [[self alloc] init];
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
    _startNs = (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;
    return t;
}

- (double)elapsedMilliseconds {
    struct timespec ts;
    clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
    uint64_t now = (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;
    return (now - _startNs) / 1000000.0;
}
@end

4. Legacy: mach_absolute_time() with timebase conversion

Only use this if you must support iOS < 10 or macOS < 10.12. It requires a one-time mach_timebase_info call to convert ticks to nanoseconds.

#include <mach/mach_time.h>

static mach_timebase_info_data_t timebase;

uint64_t now_ns(void) {
    if (timebase.denom == 0) {
        mach_timebase_info(&timebase);
    }
    return mach_absolute_time() * timebase.numer / timebase.denom;
}

CACurrentMediaTime() internally uses this same clock but hides the conversion.

5. What to avoid: NSDate / Date() for intervals

// ❌ Bad for sub-millisecond work
let start = Date()
// …
let ms = -start.timeIntervalSinceNow * 1000 // wall-clock, ~1 ms resolution

Date() reads the real-time clock, which can jump forward or backward. It is fine for timestamps shown to users, but not for measuring elapsed time.

How to prevent it

  • Default to ContinuousClock in Swift code targeting iOS 16/macOS 13 or later.
  • Use CACurrentMediaTime() when the measurement is tied to Core Animation callbacks (CADisplayLink, UIView animation blocks, UIScrollViewDelegate).
  • Drop to clock_gettime(CLOCK_MONOTONIC_RAW) only when you need raw nanoseconds in C/Objective-C without QuartzCore.
  • Never use Date(), NSDate, or CFAbsoluteTimeGetCurrent() for interval measurements.
  • Cache the mach_timebase_info result if you ever use mach_absolute_time() directly.

FAQ

Is CACurrentMediaTime() the same as mach_absolute_time()?

Yes, CACurrentMediaTime() is a thin wrapper that converts mach_absolute_time() ticks to seconds using the system timebase. It is monotonic and suitable for UI timing.

Can I use ContinuousClock on Linux or Windows?

Yes. ContinuousClock is part of the Swift standard library and maps to clock_gettime(CLOCK_MONOTONIC) on Linux and QueryPerformanceCounter on Windows, giving you cross-platform monotonic timing with the same API.

Why does my scroll-speed calculation jitter when the device goes to sleep?

If you used Date() or CFAbsoluteTimeGetCurrent(), the wall clock jumps when the system wakes. Switch to CACurrentMediaTime() or ContinuousClock; both pause during sleep and resume monotonically, eliminating the jump.

Sources & credits

Parts of this guide are adapted from content licensed under CC BY-SA 3.0; this article is shared under the same license.