1

我在我的程序中使用 gettimeofday 这样的时间间隔:

struct timeval currentTime, startTime; 
gettimeofday(&startTime, NULL);
startTime.tv_usec /= 1000;
gettimeofday(&currentTime, NULL);
currentTime.tv_usec /= 1000;

long int msSinceStart = (currentTime.tv_usec + (1000 * currentTime.tv_sec) ) - (startTime.tv_usec + (1000 * startTime.tv_sec) );

有没有其他选择?

4

4 回答 4

3

@user2282782 在他们的评论中指出,问题背后的真正问题是gettimeofday is invalid in c99在编译时发出警告。

正如@Emmanuel 指出的那样,要解决这个问题,只需
#include <sys/time.h>在文件顶部添加:。这也解决了我同样的问题。

于 2015-12-15T19:37:00.927 回答
2

您还可以使用CFAbsoluteTimeGetCurrent

CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();

并获取经过的秒数:

CFTimeInterval elapsed = CFAbsoluteTimeGetCurrent() - start;

请注意,文档警告CFAbsoluteTimeGetCurrent我们:

重复调用此函数并不能保证结果单调递增。由于与外部时间参考同步或由于用户明确更改时钟,系统时间可能会减少。

这意味着,如果您不幸在其中一项调整发生时测量了经过的时间,您最终可能会得到不正确的经过时间计算。此警告也适用于NSDate类似的功能。要解决此问题,您可以使用CACurrentMediaTime

CFTimeInterval start = CACurrentMediaTime();

CFTimeInterval elapsed = CACurrentMediaTime() - start;

这使用mach_absolute_time但避免了技术问答 QA1398中概述的一些复杂性。

于 2014-03-20T12:48:36.100 回答
1

Objective-C 的替代方案是 NSDate。

NSDate *startTime = [NSDate date];
NSTimeInterval secondsSinceStart = -[startTime timeIntervalSinceNow];

当然,如果你想要一个高分辨率的时间,你应该使用 mach_absolute_time (见https://developer.apple.com/library/mac/qa/qa1398/_index.html)。

于 2014-03-20T12:42:38.437 回答
1

现在要解决此问题,您应该将以下内容插入到您的文件中:

#import <UIKit/UIKit.h>

于 2018-08-06T19:38:50.060 回答