Skip to content

Instantly share code, notes, and snippets.

@nevyn
Created July 10, 2014 11:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nevyn/f78bc884994ba4a01979 to your computer and use it in GitHub Desktop.
Save nevyn/f78bc884994ba4a01979 to your computer and use it in GitHub Desktop.
Don't use [NSDate timeIntervalFromReferenceDate] if you're working with deltas or timing or anything that isn't directly date related. Use absolute, monotonically increasing time instead. Using mach time is easy but slightly inconvenient; here's a very simple NSDate-like class you can use in your code.
#import <Foundation/Foundation.h>
@interface GFClock : NSObject
+ (instancetype)sharedClock;
// since device boot or something. Monotonically increasing, unaffected by date and time settings
- (NSTimeInterval)absoluteTime;
@end
#import "GFClock.h"
#include <mach/mach.h>
#include <mach/mach_time.h>
@implementation GFClock
{
mach_timebase_info_data_t _clock_timebase;
}
+ (instancetype)sharedClock
{
static GFClock *g;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
g = [GFClock new];
});
return g;
}
- (id)init
{
if(!(self = [super init]))
return nil;
mach_timebase_info(&_clock_timebase);
return self;
}
- (NSTimeInterval)absoluteTime
{
uint64_t machtime = mach_absolute_time();
uint64_t nanos = (machtime * _clock_timebase.numer) / _clock_timebase.denom;
return nanos/1.0e9;
}
@end
@intelliot
Copy link

How about CACurrentMediaTime()?

@kainjow
Copy link

kainjow commented Aug 7, 2018

Could use NSEC_PER_SEC instead of 1.0e9.

@intelliot seems odd to link against Core Animation for something that doesn't use animation?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment