为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

九州编程 2019-09-21 15:09:40
有没有一种简单的方法可以精确地获取时间?我需要计算两次方法调用之间的延迟。更具体地说,我想计算UIScrollView中的滚动速度。
查看完整描述

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类参考。


查看完整回答
反对 回复 2019-09-21
?
德玛西亚99

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


查看完整回答
反对 回复 2019-09-21
  • 3 回答
  • 0 关注
  • 1525 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信