iOS時間計測ログをつくる

処理時間を計算するためのログをつくります。

どうやらObjective-C単独のコードで作れないようで, Cの力(gettimeofday)を借りねばならないようです。
NSDate *date = [NSDate date] という方法で時間を取得し, その差分でもいけますが, 計測処理という点では不十分です。
これ自体に処理の時間もかかりますし。

1. インスタンス作成時に計測を開始

2. 処理と処理の間の時間を計測

3. 最初の処理と現在の処理との時間を計測する

という仕様でつくります。

TimeLog.h

#import <Foundation/Foundation.h>
#import <sys/time.h>


@interface TimeLog : NSObject

@property (nonatomic) struct timeval first;
@property (nonatomic) struct timeval previous;

-(void)log:(NSString *)message;
-(void)finish;

@end

非常にシンプルです。最初に計測するための時間と一つ前の処理をキープするための変数を用意します。
sys/time を import しておきます。

TimeLog.m

@implementation TimeLog

@synthesize first;
@synthesize previous;

-(id)init
{
    if ( self == [super init] )
    {
        gettimeofday(&first, NULL);
        gettimeofday(&previous, NULL);
    }
    return self;
}

-(void)log:(NSString *)message
{
    struct timeval now;
    gettimeofday(&now, NULL);
    
    double start = previous.tv_sec * 1000 + previous.tv_usec * 1e-3;
    double finish = now.tv_sec * 1000 + now.tv_usec * 1e-3;
    NSLog(@"Check Point: %f ms - %@", finish - start, message);
    gettimeofday(&previous, NULL);
}

-(void)finish
{
    struct timeval now;
    gettimeofday(&now, NULL);
    
    double start = first.tv_sec * 1000 + first.tv_usec * 1e-3;
    double finish = now.tv_sec * 1000 + now.tv_usec * 1e-3;
    NSLog(@"Final: %f ms - from beggining", finish - start);
    gettimeofday(&previous, NULL);
}

@end

NSLogを使ってログをとっています。gettimeofday で現在の時刻を取得しています。
あとはms に変換して, 差分をとります。

使用方法(ARCの場合)

TimeLog *log = [[TimeLog alloc] init];
[log log:@"start"];
// Process
[log log:@"end"];
[log finish];

使用方法(ARCでない場合)

TimeLog *log = [[TimeLog alloc] init];
[log log:@"start"];
// Process
[log log:@"end"];
[log finish];
[log release];

AppDelegateでstatic などにすれば, アプリケーション全体で計測も可能です。