我如何计算iOS中的时间?

Nor*_*der 2 objective-c nsdate nstimer nstimeinterval ios

在一段时间过后,我不想设置一个"触发"(并做某事)的计时器.

因此,我对NSTimer课程及其方法不感兴趣.

所有我感兴趣的是计算经过的时间,例如,一些while循环正在执行.NSDate我猜可以使用如下:

NSDate currentDate = [[NSDate alloc] init];

while(someConditionIsTrue)
{
    // executing..
}

timeElapsed = [self timeIntervalSinceDate:currentDate];

NSLog(@"time elapsed was: %i", timeElapsed);
Run Code Online (Sandbox Code Playgroud)

但是,如果我理解正确,timeIntervalSinceDate:只能计算秒数.

有没有办法可以计算在几毫秒内经过的时间?

换句话说,我可以计算的最小单位是什么?

max*_*ax_ 9

看看CFAbsoluteTimeGetCurrent()

CFAbsoluteTime before = CFAbsoluteTimeGetCurrent();
CFAbsoluteTime after = CFAbsoluteTimeGetCurrent();
Run Code Online (Sandbox Code Playgroud)

  • 实际上,`[NSDate timeIntervalSinceReferenceDate]`可能直接映射到CFAbsoluteTimeGetCurrent,因为它们返回相同的值. (2认同)

Dru*_*erB 7

你的第二种方法是正确的.将当前日期保存在NSDate对象中并用于timeIntervalSinceDate:获取自那时起的传递时间.结果将NSTimeInterval是浮点数类型.它以秒为单位指定时间差,但由于它是一个浮点数,因此它也可以存储几分之一秒.

NSTimeInterval始终以秒为单位指定; 它在10,000年的范围内产生亚毫秒精度.