Skip to content

Instantly share code, notes, and snippets.

@vigorouscoding
Last active August 29, 2015 13:57
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save vigorouscoding/017232caf4a2146d0c15 to your computer and use it in GitHub Desktop.
Block-based timing function - easily compare the runtime for different code paths or snippets
#import <Foundation/Foundation.h>
@interface KSTimingHelper : NSObject
// Thanks to Mattt Thompson -> http://nshipster.com/benchmarking/
extern uint64_t dispatch_benchmark(size_t count, void (^block)(void));
+(unsigned long long)timeForBlock:(void (^)(void))actions;
+(unsigned long long)timeForBlock:(void (^)(void))actions runCount:(NSUInteger)runCount;
+(void)printTimeForBlock:(void (^)(void))actions;
+(void)printTimeForBlock:(void (^)(void))actions runCount:(NSUInteger)runCount;
+(void)printTimeForBlock:(void (^)(void))actions withTitle:(NSString *)title;
+(void)printTimeForBlock:(void (^)(void))actions withTitle:(NSString *)title runCount:(NSUInteger)runCount;
@end
#import "KSTimingHelper.h"
@implementation KSTimingHelper
+(unsigned long long)timeForBlock:(void (^)(void))actions {
return dispatch_benchmark(1, actions);
}
+(unsigned long long)timeForBlock:(void (^)(void))actions runCount:(NSUInteger)runCount {
return dispatch_benchmark(runCount, actions);
}
+(void)printTimeForBlock:(void (^)(void))actions {
NSLog(@"Time: %lld", [KSTimingHelper timeForBlock:actions]);
}
+(void)printTimeForBlock:(void (^)(void))actions runCount:(NSUInteger)runCount {
NSLog(@"Time (%d runs): %lld", runCount, [KSTimingHelper timeForBlock:actions]);
}
+(void)printTimeForBlock:(void (^)(void))actions withTitle:(NSString *)title {
NSLog(@"[%@] Time: %lld", title, [KSTimingHelper timeForBlock:actions]);
}
+(void)printTimeForBlock:(void (^)(void))actions withTitle:(NSString *)title runCount:(NSUInteger)runCount {
NSLog(@"[%@ run %d times] Time: %lld", title, runCount, [KSTimingHelper timeForBlock:actions]);
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment