Skip to content

Instantly share code, notes, and snippets.

@bignerdranch
Created March 9, 2012 13:51
Show Gist options
  • Star 81 You must be signed in to star a gist
  • Fork 10 You must be signed in to fork a gist
  • Save bignerdranch/2006587 to your computer and use it in GitHub Desktop.
Save bignerdranch/2006587 to your computer and use it in GitHub Desktop.
Timing Utility Post 20120308
CGFloat BNRTimeBlock (void (^block)(void));
#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
@markd2
Copy link

markd2 commented Aug 11, 2016

Here's a swift version:

func BNRTimeBlock(_ block: @noescape () -> Void) -> TimeInterval {
    var info = mach_timebase_info()
    guard mach_timebase_info(&info) == KERN_SUCCESS else { return -1 }

    let start = mach_absolute_time()
    block()
    let end = mach_absolute_time()

    let elapsed = end - start

    let nanos = elapsed * UInt64(info.numer) / UInt64(info.denom)
    return TimeInterval(nanos) / TimeInterval(NSEC_PER_SEC)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment