What is the closest Swift equivalent of the following C & OpenMP code (assume that n
is huge and f
is simple):
#openmp parallel for
for (int i = 0; i < n; ++i) {
a[i] = f(b[i]);
}
Parallelising a for loop with striding and dispatch_apply
seems like a lot of work for such a routine task. Is there any clever shortcut?
If your code has loops, and the work being done each time through the loop is independent of the work being done in the other iterations, you might consider reimplementing that loop code using the dispatch_apply or dispatch_apply_f function. These functions submit each iteration of a loop separately to a dispatch queue for processing. When used in conjunction with a concurrent queue, this feature lets you perform multiple iterations of the loop concurrently.
Read here: https://developer.apple.com/library/content/documentation/General/Conceptual/ConcurrencyProgrammingGuide/ThreadMigration/ThreadMigration.html#//apple_ref/doc/uid/TP40008091-CH105-SW2
For swift: https://developer.apple.com/documentation/dispatch/dispatchqueue/2016088-concurrentperform
DispatchQueue.concurrentPerform(iterations: 1000) { (index) in
print("current: \(index)")
}
It appears (from the iBook) that there's not yet a swift-specific API/language feature for parallelism. Using GCD seems like the best option at this point, performance-wise. If you're looking for code brevity, you can just use the standard Objective-C idiom for concurrent array enumeration:
var array : Int[] = [1,2,3,4]
array.bridgeToObjectiveC().enumerateObjectsWithOptions(NSEnumerationOptions.Concurrent, {(obj: AnyObject!, index: Int, outStop: CMutablePointer<ObjCBool>) -> Void in
// Do stuff
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With