ios 在 Objective-C 中获取时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/741830/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 15:48:09  来源:igfitidea点击:

Getting time elapsed in Objective-C

iosobjective-c

提问by Ilya Suzdalnitski

I need to get the time elapsed between two events, for example, the appearance of a UIView and the user's first reaction.

我需要获取两个事件之间经过的时间,例如 UIView 的出现和用户的第一反应。

How can I achieve it in Objective-C?

我怎样才能在 Objective-C 中实现它?

回答by Can Berk Güder

NSDate *start = [NSDate date];
// do stuff...
NSTimeInterval timeInterval = [start timeIntervalSinceNow];

timeIntervalis the difference between start and now, in seconds, with sub-millisecond precision.

timeInterval是 start 和 now 之间的差异,以秒为单位,精度为亚毫秒。

回答by Senseful

You should not rely on [NSDate date]for timing purposes since it can over- or under-report the elapsed time. There are even cases where your computer will seemingly time-travel since the elapsed time will be negative! (E.g. if the clock moved backwards during timing.)

您不应该依赖[NSDate date]计时目的,因为它可能会高估或低估经过的时间。甚至在某些情况下,您的计算机似乎会进行时间旅行,因为经过的时间将为负数!(例如,如果时钟在计时期间向后移动。)

According to Aria Haghighi in the "Advanced iOS Gesture Recognition" lecture of the Winter 2013 Stanford iOS course(34:00), you should use CACurrentMediaTime()if you need an accurate time interval.

根据Aria Haghighi在2013年冬季斯坦福iOS课程(34:00)的“高级iOS手势识别”讲座中的说法,CACurrentMediaTime()如果需要准确的时间间隔,则应使用。

Objective-C:

目标-C:

#import <QuartzCore/QuartzCore.h>
CFTimeInterval startTime = CACurrentMediaTime();
// perform some action
CFTimeInterval elapsedTime = CACurrentMediaTime() - startTime;

Swift:

迅速:

let startTime = CACurrentMediaTime()
// perform some action
let elapsedTime = CACurrentMediaTime() - startTime

The reason is that [NSDate date]syncs on the server, so it could lead to "time-sync hiccups" which can lead to very difficult-to-track bugs. CACurrentMediaTime(), on the other hand, is a device time that doesn't change with these network syncs.

原因是[NSDate date]服务器上的同步,所以它可能导致“时间同步打嗝”,这可能导致非常难以跟踪的错误。CACurrentMediaTime()另一方面,设备时间不会随着这些网络同步而改变。

You will need to addthe QuartzCore frameworkto your target's settings.

您将需要添加QuartzCore框架到目标的设置。

回答by Marco Lazzeri

Use the timeIntervalSinceDatemethod

使用timeIntervalSinceDate方法

NSTimeInterval secondsElapsed = [secondDate timeIntervalSinceDate:firstDate];

NSTimeIntervalis just a double, define in NSDatelike this:

NSTimeInterval只是一个doubleNSDate像这样定义:

typedef double NSTimeInterval;

回答by Wayne Uroda

For anybody coming here looking for a getTickCount() implementation for iOS, here is mine after putting various sources together.

对于来这里寻找 iOS 的 getTickCount() 实现的任何人来说,这是我将各种来源放在一起后的。

Previously I had a bug in this code (I divided by 1000000 first) which was causing some quantisation of the output on my iPhone 6 (perhaps this was not an issue on iPhone 4/etc or I just never noticed it). Note that by not performing that division first, there is some risk of overflow if the numerator of the timebase is quite large. If anybody is curious, there is a link with much more information here: https://stackoverflow.com/a/23378064/588476

以前我在这段代码中有一个错误(我先除以 1000000),它导致我的 iPhone 6 上的输出有些量化(也许这不是 iPhone 4/etc 上的问题,或者我只是从未注意到它)。请注意,如果不先执行该除法,则如果时基的分子非常大,则存在溢出的风险。如果有人好奇,这里有一个包含更多信息的链接:https: //stackoverflow.com/a/23378064/588476

In light of that information, maybe it is safer to use Apple's function CACurrentMediaTime!

根据这些信息,也许使用 Apple 的功能更安全CACurrentMediaTime

I also benchmarked the mach_timebase_infocall and it takes approximately 19ns on my iPhone 6, so I removed the (not threadsafe) code which was caching the output of that call.

我还对mach_timebase_info调用进行了基准测试,它在我的 iPhone 6 上花费了大约 19ns,所以我删除了缓存该调用输出的(非线程安全)代码。

#include <mach/mach.h>
#include <mach/mach_time.h>

uint64_t getTickCount(void)
{
    mach_timebase_info_data_t sTimebaseInfo;
    uint64_t machTime = mach_absolute_time();

    // Convert to milliseconds
    mach_timebase_info(&sTimebaseInfo);
    machTime *= sTimebaseInfo.numer;
    machTime /= sTimebaseInfo.denom;
    machTime /= 1000000; // convert from nanoseconds to milliseconds

    return machTime;
}

Do be aware of the potential risk of overflow depending on the output of the timebase call. I suspect (but do not know) that it might be a constant for each model of iPhone. on my iPhone 6 it was 125/3.

请注意根据时基调用输出的潜在溢出风险。我怀疑(但不知道)对于每种型号的 iPhone,它可能都是一个常数。在我的 iPhone 6 上它是125/3

The solution using CACurrentMediaTime()is quite trivial:

使用的解决方案CACurrentMediaTime()非常简单:

uint64_t getTickCount(void)
{
    double ret = CACurrentMediaTime();
    return ret * 1000;
}

回答by Jason Coco

For percise time measurements (like GetTickCount), also take a look at mach_absolute_time and this Apple Q&A: http://developer.apple.com/qa/qa2004/qa1398.html.

对于精确的时间测量(如 GetTickCount),还可以查看 mach_absolute_time 和这个 Apple Q&A:http: //developer.apple.com/qa/qa2004/qa1398.html

回答by Raj

use the timeIntervalSince1970 function of the NSDate class like below:

使用 NSDate 类的 timeIntervalSince1970 函数,如下所示:

double start = [startDate timeIntervalSince1970];
double end = [endDate timeIntervalSince1970];
double difference = end - start;

basically, this is what i use to compare the difference in seconds between 2 different dates. also check this link here

基本上,这就是我用来比较 2 个不同日期之间的秒数差异的方法。也在这里检查这个链接

回答by Basil Bourque

The other answers are correct (with a caveat*). I add this answer simply to show an example usage:

其他答案是正确的(有一个警告*)。我添加这个答案只是为了展示一个示例用法:

- (void)getYourAffairsInOrder
{
    NSDate* methodStart = [NSDate date];  // Capture start time.

    // … Do some work …

    NSLog(@"DEBUG Method %s ran. Elapsed: %f seconds.", __func__, -([methodStart timeIntervalSinceNow]));  // Calculate and report elapsed time.
}

On the debugger console, you see something like this:

在调试器控制台上,您会看到如下内容:

DEBUG Method '-[XMAppDelegate getYourAffairsInOrder]' ran. Elapsed: 0.033827 seconds.


*Caveat: As others mentioned, use NSDateto calculate elapsed time only for casual purposes. One such purpose might be common testing, crude profiling, where you just want a rough idea of how long a method is taking.

*警告:正如其他人提到的,用于NSDate计算经过时间仅用于临时目的。一个这样的目的可能是常见的测试、粗略的分析,您只是想粗略地了解一种方法需要多长时间。

The risk is that the device's clock's current time setting could change at any moment because of network clock syncing. So NSDatetime could jump forward or backward at any moment.

风险在于设备时钟的当前时间设置可能会因网络时钟同步而随时更改。所以NSDate时间可以随时向前或向后跳跃。