Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parallel for loop in Swift

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?

like image 854
Jukka Suomela Avatar asked Jun 04 '14 12:06

Jukka Suomela


2 Answers

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)")
}
like image 136
mazy Avatar answered Nov 05 '22 12:11

mazy


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
    });
like image 20
ipmcc Avatar answered Nov 05 '22 11:11

ipmcc