Created
July 23, 2011 15:26
-
-
Save m0wfo/1101546 to your computer and use it in GitHub Desktop.
Round 2- parallel divide & conquer reduction function
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- (id)reduceWithBlock:(id (^)(id memo, id obj))block andAccumulator:(id)accumulator withBaseLength:(NSUInteger)baseLength | |
{ | |
__block id acc = [[accumulator copy] autorelease]; | |
NSUInteger base_job_length = baseLength; | |
if (!baseLength) { | |
// Calculate the base job length | |
NSUInteger num_processors = [[NSProcessInfo processInfo] processorCount]; | |
base_job_length = (NSUInteger)([self count] / sqrt(num_processors)); // (L = n / p squared) | |
} | |
if ([self count] <= base_job_length) { | |
// If the size of the array is <= base case, reduce it serially | |
for (id obj in self) { acc = block(acc, obj); } | |
} else { | |
// If the array length is > base case, divide & conquer | |
NSArray* sub_jobs = [self splitIntoSubArraysOfLength:base_job_length]; | |
dispatch_queue_t result_queue = dispatch_queue_create(NULL, DISPATCH_QUEUE_CONCURRENT); | |
dispatch_apply([sub_jobs count], result_queue, ^(size_t i) { | |
acc = block(acc, [[sub_jobs objectAtIndex:i] reduceWithBlock:block andAccumulator:accumulator withBaseLength:base_job_length]); | |
}); | |
dispatch_release(result_queue); | |
} | |
return acc; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment