Note that there are some explanatory texts on larger screens.

plurals
  1. POCalculating number of seconds between two points in time, in Cocoa, even when system clock has changed mid-way
    text
    copied!<p>I'm writing a Cocoa OS X (Leopard 10.5+) end-user program that's using timestamps to calculate statistics for how long something is being displayed on the screen. Time is calculated periodically while the program runs using a repeating NSTimer. <code>[NSDate date]</code> is used to capture timestamps, <strong>Start</strong> and <strong>Finish</strong>. Calculating the difference between the two dates in seconds is trivial.</p> <p>A problem occurs if an end-user or ntp changes the system clock. <code>[NSDate date]</code> relies on the system clock, so if it's changed, the <strong>Finish</strong> variable will be skewed relative to the <strong>Start</strong>, messing up the time calculation significantly. My question:</p> <p><strong>1. How can I accurately calculate the time between <em>Start</em> and <em>Finish</em>, in seconds, even when the system clock is changed mid-way?</strong></p> <p>I'm thinking that I need a non-changing reference point in time so I can calculate how many seconds has passed since then. For example, system uptime. 10.6 has <code>- (NSTimeInterval)systemUptime</code>, part of <code>NSProcessInfo</code>, which provides system uptime. However, this won't work as my app must work in 10.5.</p> <p>I've tried creating a time counter using NSTimer, but this isn't accurate. NSTimer has several different run modes and can only run one at a time. NSTimer (by default) is put into the <em>default</em> run mode. If a user starts manipulating the UI for a long enough time, this will enter <em>NSEventTrackingRunLoopMode</em> and skip over the <em>default</em> run mode, which can lead to NSTimer firings being skipped, making it an inaccurate way of counting seconds.</p> <p>I've also thought about creating a separate thread (NSRunLoop) to run a NSTimer second-counter, keeping it away from UI interactions. But I'm very new to multi-threading and I'd like to stay away from that if possible. Also, I'm not sure if this would work accurately in the event the CPU gets pegged by another application (Photoshop rendering a large image, etc...), causing my NSRunLoop to be put on hold for long enough to mess up its NSTimer.</p> <p>I appreciate any help. :)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload