Created
July 10, 2014 11:33
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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 |
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
How about
CACurrentMediaTime()
?