/ 猿问

# 如何获得精确的时间，例如在Objective-C中以毫秒为单位？

2019-09-21 15:09:40

## 3 回答

NSDate并且timeIntervalSince*方法将返回a NSTimeInterval，该精度为毫秒以下精度的两倍。NSTimeInterval以秒为单位，但是它使用双精度来提高精度。

// Get a current time for where you want to start measuring from

NSDate *date = [NSDate date];

// do work...

// Find elapsed time and convert to milliseconds

// Use (-) modifier to conversion since receiver is earlier than now

double timePassed_ms = [date timeIntervalSinceNow] * -1000.0;

timeIntervalSinceNow上的文档。

mach_absolute_time() 可用于获得精确的测量值。

// LBClock.h

@interface LBClock : NSObject

+ (instancetype)sharedClock;

// since device boot or something. Monotonically increasing, unaffected by date and time settings

- (NSTimeInterval)absoluteTime;

- (NSTimeInterval)machAbsoluteToTimeInterval:(uint64_t)machAbsolute;

@end

// LBClock.m

#include <mach/mach.h>

#include <mach/mach_time.h>

@implementation LBClock

{

mach_timebase_info_data_t _clock_timebase;

}

+ (instancetype)sharedClock

{

static LBClock *g;

static dispatch_once_t onceToken;

dispatch_once(&onceToken, ^{

g = [LBClock new];

});

return g;

}

- (id)init

{

if(!(self = [super init]))

return nil;

mach_timebase_info(&_clock_timebase);

return self;

}

- (NSTimeInterval)machAbsoluteToTimeInterval:(uint64_t)machAbsolute

{

uint64_t nanos = (machAbsolute * _clock_timebase.numer) / _clock_timebase.denom;

return nanos/1.0e9;

}

- (NSTimeInterval)absoluteTime

{

uint64_t machtime = mach_absolute_time();

return [self machAbsoluteToTimeInterval:machtime];

}

@end

• 3 回答
• 0 关注
• 385 浏览

0/150