xcode 用于测量 iPad 或手机上代码内部精确执行时间的代码?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4773654/
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
Code to measure EXACT execution time inside code on iPad or Phone?
提问by Fattie
Is is any difference between using mach_absolute_timeand the simple NSDatemethod explained by golden eagle below?
使用mach_absolute_time和下面金鹰解释的简单NSDate方法有什么区别吗?
Here's an excellent explanation of using the mach approach...
这是使用 mach 方法的一个很好的解释......
How do I accurately time how long it takes to call a function on the iPhone?
and
和
回答by Aurum Aquila
loop
{
NSDate *start = [NSDate date];
// a considerable amount of difficult processing here
// a considerable amount of difficult processing here
// a considerable amount of difficult processing here
NSDate *methodFinish = [NSDate date];
NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:start];
NSLog(@"Execution Time: %f", executionTime);
}
Should work.
应该管用。
回答by Nikolay Shubenkov
Upon previous answear I have implemented a simple class to measure time
在之前的回答中,我实现了一个简单的类来测量时间
How it works:
这个怎么运作:
ABTimeCounter *timer = [ABTimeCounter new];
[timer restart];
//do some calculations
[timer pause];
//do some other staff
[timer resume];
//other code
//You can measure current time immediately
NSLog(@"Time left from starting calculations: %f seconds",[timer measuredTime]);
[timer pause];
your .h file should look like this:
您的 .h 文件应如下所示:
@interface ABTimeCounter : NSObject
@property (nonatomic, readonly) NSTimeInterval measuredTime;
- (void)restart;
- (void)pause;
- (void)resume;
@end
.m file:
.m 文件:
@interface ABTimeCounter ()
@property (nonatomic, strong) NSDate *lastStartDate;
@property (nonatomic) BOOL isCounting;
@property (nonatomic, readwrite) NSTimeInterval accumulatedTime;
@end
@implementation ABTimeMeasure
#pragma mark properties overload
- (NSTimeInterval) measuredTime
{
return self.accumulatedTime + [self p_timeSinceLastStart];
}
#pragma mark - public -
- (void) restart
{
self.accumulatedTime = 0;
self.lastStartDate = [NSDate date];
self.isCounting = YES;
}
- (void) pause
{
if (self.isCounting){
self.accumulatedTime += [self p_timeSinceLastStart];
self.lastStartDate = nil;
self.isCounting = NO;
}
}
- (void) resume
{
if (!self.isCounting){
self.lastStartDate = [NSDate date];
self.isCounting = YES;
}
}
#pragma mark - private -
- (NSTimeInterval) p_timeSinceLastStart
{
if (self.isCounting){
return [[NSDate date] timeIntervalSinceDate:self.lastStartDate];
}
else return 0;
}
@end