Skip to content

Instantly share code, notes, and snippets.

@Norod
Created July 11, 2014 18:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Norod/3c542e0c57a281a5433e to your computer and use it in GitHub Desktop.
Save Norod/3c542e0c57a281a5433e to your computer and use it in GitHub Desktop.
Benchmark average time of [array firstObject] calls and [array lastObject] calls. Result - Sim: No difference, iPad 2: 0.9% - 2.1% in favour of firstObject
//
// ViewController.m
// testDispatchBenchmark
//
// Created by Doron Adler on 7/11/14.
//
#import "ViewController.h"
#include <mach/mach.h>
#include <mach/mach_time.h>
@implementation ViewController
typedef struct _t_pair_avg_elapsed_nano
{
uint64_t t_0_avg_elapsed_nano;
uint64_t t_1_avg_elapsed_nano;
}t_pair_avg_elapsed_nano, *t_pair_avg_elapsed_nano_ptr;
- (t_pair_avg_elapsed_nano) performBenchmarkIterations:(size_t)iterations{
t_pair_avg_elapsed_nano result = {0,0};
static mach_timebase_info_data_t sTimebaseInfo;
if ( sTimebaseInfo.denom == 0 ) {
(void) mach_timebase_info(&sTimebaseInfo);
}
NSArray *array = @[@0, @1, @2, @3, @4, @5, @6, @7, @8, @9];
/////// firstObject
uint64_t t_0 = mach_absolute_time();
for (size_t i = 0 ; i < iterations; i++) {
NSNumber *firstObject = nil;
firstObject = [array firstObject];
}
result.t_0_avg_elapsed_nano = ((mach_absolute_time() - t_0) * sTimebaseInfo.numer) / sTimebaseInfo.denom;
result.t_0_avg_elapsed_nano /= iterations;
/////// lastObject
uint64_t t_1 = mach_absolute_time();
for (size_t i = 0 ; i < iterations; i++) {
NSNumber *lastObject = nil;
lastObject = [array lastObject];
}
result.t_1_avg_elapsed_nano = ((mach_absolute_time() - t_1) * sTimebaseInfo.numer) / sTimebaseInfo.denom;
result.t_1_avg_elapsed_nano /= iterations;
return result;
}
- (IBAction) performBenchmark:(id)sender{
static size_t numberOfTests = 100000;
static size_t iterationsPerTest = 1000;
__block uint64_t t_0_total_elapsed_nano = 0;
__block uint64_t t_1_total_elapsed_nano = 0;
dispatch_queue_t backgroundQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0);
dispatch_async(backgroundQueue, ^{
for (size_t i = 0 ; i < numberOfTests; i++) {
@autoreleasepool {
t_pair_avg_elapsed_nano testResult;
testResult = [self performBenchmarkIterations:iterationsPerTest];
t_0_total_elapsed_nano += testResult.t_0_avg_elapsed_nano;
t_1_total_elapsed_nano += testResult.t_1_avg_elapsed_nano;
}
}
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"The results for %zu tests with %zu iterations each are:", numberOfTests, iterationsPerTest); //TODO: Add drum roll :p
NSLog(@"[array firstObject] - Each call took an avg of %llu ns to run", (t_0_total_elapsed_nano / numberOfTests));
NSLog(@"[array lastObject] - Each call took an avg of %llu ns to run", (t_1_total_elapsed_nano / numberOfTests));
});
});
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment