简体   繁体   English

我如何计算iOS中的时间?

[英]How do I count time in iOS?

I don't want to set up a timer that "fires" (and does something) after a certain amount of time has passed. 在一段时间过后,我不想设置一个“触发”(并做某事)的计时器。

Therefore, I'm not interested in the NSTimer class and its methods. 因此,我对NSTimer类及其方法不感兴趣。

All I'm interested in is counting the time that passes by while , for example, some while-loop is executing. 所有我感兴趣的是计算经过的时间 ,例如,一些while循环正在执行。 I could use NSDate as follows I guess : 我可以使用NSDate ,如下所示:

NSDate currentDate = [[NSDate alloc] init];

while(someConditionIsTrue)
{
    // executing..
}

timeElapsed = [self timeIntervalSinceDate:currentDate];

NSLog(@"time elapsed was: %i", timeElapsed);

However, if I understand correctly, timeIntervalSinceDate: can only count seconds. 但是,如果我理解正确, timeIntervalSinceDate:只能计算秒数。

Is there a way I can count the time that is passing by in milliseconds ? 有没有办法可以计算在几毫秒内经过的时间?

In other words, what is the smallest unit I can count passing time in and how ? 换句话说, 我可以计算的最小单位是什么?

Look at CFAbsoluteTimeGetCurrent() 看看CFAbsoluteTimeGetCurrent()

CFAbsoluteTime before = CFAbsoluteTimeGetCurrent();
CFAbsoluteTime after = CFAbsoluteTimeGetCurrent();

Your second approach is correct. 你的第二种方法是正确的。 Save the current date in an NSDate object and use timeIntervalSinceDate: to get the passed time since then. 将当前日期保存在NSDate对象中,并使用timeIntervalSinceDate:来获取自那时起的传递时间。 The result will be of type NSTimeInterval which is a floating point number. 结果将是NSTimeInterval类型,它是一个浮点数。 It specifies time differences in seconds, but since it's a floating point number it can store fractions of a second as well. 它以秒为单位指定时间差,但由于它是一个浮点数,因此它也可以存储几分之一秒。

NSTimeInterval is always specified in seconds; NSTimeInterval始终以秒为单位指定; it yields sub-millisecond precision over a range of 10,000 years. 它在10,000年的范围内产生亚毫秒精度。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM