最後在做一個應用的時候,從電話本時讀出數據,如果電話很多,就需要比較長的時間,於是如果能得到每個方法的執行時間,就可以知道代碼優化的地方。
在網上看到了一個比較好的方法來獲取執行時間。看代碼
- #import <mach/mach_time.h> // for mach_absolute_time() and friends
-
- CGFloat BNRTimeBlock (void (^block)(void)) {
- mach_timebase_info_data_t info;
- if (mach_timebase_info(&info) != KERN_SUCCESS) return -1.0;
-
- uint64_t start = mach_absolute_time ();
- block ();
- uint64_t end = mach_absolute_time ();
- uint64_t elapsed = end - start;
-
- uint64_t nanos = elapsed * info.numer / info.denom;
- return (CGFloat)nanos / NSEC_PER_SEC;
-
- } // BNRTimeBlock
調用方法如下
- #define LOOPAGE 10000000
-
- #import "BNRTimeBlock.h"
-
- int main (void) {
- CGFloat time;
-
- NSString *thing1 = @"hi";
- NSString *thing2 = @"hello there";
-
- time = BNRTimeBlock(^{
- for (int i = 0; i < LOOPAGE; i++) {
- [thing1 isEqual: thing2];
- }
- });
- printf ("isEqual: time: %f\n", time);
-
- time = BNRTimeBlock(^{
- for (int i = 0; i < LOOPAGE; i++) {
- [thing1 isEqualToString: thing2];
- }
- });
- printf ("isEqualToString: time: %f\n", time);
-
- return 0;
- } // main