Skip to content

Instantly share code, notes, and snippets.

@kimhunter
Created November 6, 2012 22:56
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kimhunter/4028245 to your computer and use it in GitHub Desktop.
Save kimhunter/4028245 to your computer and use it in GitHub Desktop.
Compare Dispatch Concurrent to for loop
#import <Foundation/Foundation.h>
#define LOGV(V) NSLog(@"%s = %@", #V, V);
#define LOGD(I) NSLog(@"%s = %d", #I, I);
int main(int argc, const char * argv[])
{
@autoreleasepool
{
dispatch_queue_t dqueue = NULL;
size_t size = 24772188; // decrease for iOS
NSMutableArray *array = [NSMutableArray array];
NSDate *startDate;
NSMutableArray *useableArray;
// build an array
for (size_t i = 0; i <= size; ++i) {
[array addObject:@(i)];
}
useableArray = [array mutableCopy];
startDate = [NSDate date];
for (int i = 0; i < size; ++i)
{
useableArray[i] = @([useableArray[i] intValue] - 0.5);
}
NSLog(@"%0.3lf to - 0.5 in a for loop", [[NSDate date] timeIntervalSinceDate:startDate]);
// now try this with a concurrent queue
dqueue = dispatch_queue_create("Queue ALL THE THINGS!", DISPATCH_QUEUE_CONCURRENT);
useableArray = [array mutableCopy];
startDate = [NSDate date];
dispatch_apply(size, dqueue, ^(size_t i) {
useableArray[i] = @([useableArray[i] intValue] - 0.5);
});
NSLog(@"%0.3lf to - 0.5 in a for dispatch_apply(CONCURRENT)", [[NSDate date] timeIntervalSinceDate:startDate]);
}
}
@kimhunter
Copy link
Author

Output on my 2.7ghz i7 dual core MBP

5.589 to - 0.5 in a for loop
3.420 to - 0.5 in a for dispatch_apply(CONCURRENT)

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