.h檔

#import <mach/mach_time.h>

 

.m

使用mach_absolute_time()

 

 

- (IBAction)authHandler:(UIButton *)sender

 

{

 

    

 

    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

 

        

 

        constuint64_t startTime = mach_absolute_time();

 

        

 

        NSString *token = [selfauth];

 

        

 

        constuint64_t endTime = mach_absolute_time();

 

        constuint64_t elapsedMTU = endTime - startTime;

 

        

 

        double miliseconds = [selfMachTimeToMiliseconds:elapsedMTU];

 

        NSLog(@"Auth: %f", miliseconds);

 

        

 

        dispatch_async(dispatch_get_main_queue(), ^{

 

           

 

            self.tokenLabel.text = token;

 

        });

 

        

 

    });

 

    

 

}

 

 

 

/**

 

 * MTU轉成Miliseconds

 

 */

 

- (double)MachTimeToMiliseconds:(constuint64_t)elapsedMTU

 

{

 

    // Get information for converting from MTU to nanoseconds

 

    mach_timebase_info_data_t info;

 

    mach_timebase_info(&info);

 

    

 

    // Get elapsed time in nanoseconds:

 

    constdouble elapsedNS = (double)elapsedMTU * (double)info.numer / (double)info.denom / 1e6;

 

    

 

    return elapsedNS;

 

}

 

2016/05/09 更新:

這兩種也是可以用來測量程式執行時間

let startTime = CFAbsoluteTimeGetCurrent() (iOS 8.0 +)

let startTime = CACurrentMediaTime() (iOS 2.0 +)

 

參考資料:

1.http://stackoverflow.com/questions/3540234/high-resolution-timer-for-iphone

2.http://stackoverflow.com/questions/2129794/how-to-log-a-methods-execution-time-exactly-in-milliseconds

3.http://blog.csdn.net/lengshengren/article/details/19034401

arrow
arrow
    全站熱搜

    小賢 發表在 痞客邦 留言(0) 人氣()