3 回答

TA貢獻1856條經驗 獲得超11個贊
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上的文檔。
還有許多其他的方法來計算使用這個區間NSDate,并且我會建議在尋找的類文檔NSDate,其在被發現的NSDate類參考。

TA貢獻1770條經驗 獲得超3個贊
請不要使用NSDate,CFAbsoluteTimeGetCurrent或gettimeofday測量經過的時間。這些都依賴于系統時鐘,它可以在改變任何時間,由于許多不同的原因,諸如網絡時間同步(NTP)更新時鐘(經常發生以調整漂移),DST調整,閏秒,等等。
這意味著,如果要測量下載或上傳速度,您的數字會突然出現峰值或下降,而與實際發生的情況無關。您的性能測試將具有怪異的錯誤離群值;并且您的手動計時器將在持續時間不正確后觸發。時間甚至可能倒退,您最終會得到負增量,并且最終可能會遇到無限遞歸或無效代碼(是的,我已經完成了這兩項)。
使用mach_absolute_time。自內核啟動以來,它以秒為單位進行測量。它是單調遞增的(永遠不會向后退),并且不受日期和時間設置的影響。由于使用起來很麻煩,因此這里有一個簡單的包裝,可以為您提供NSTimeInterval:
// 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 關注
- 1785 瀏覽
添加回答
舉報