2014-11-24 32 views
3

我想圍繞如何使用GCD來並行化和加速蒙特卡羅模擬,大多數/所有簡單示例都針對Objective C我真的需要斯威夫特一個簡單的例子,因爲雨燕是我的第一個「真正」的編程語言在Swift中使用Grand Central Dispatch來並行化並加速「for」循環?

在斯威夫特蒙特卡羅模擬的最低工作版本將是這樣的:

import Foundation 

import Cocoa 
var winner = 0 
var j = 0 
var i = 0 
var chance = 0 
var points = 0 
for j=1;j<1000001;++j{ 
    var ability = 500 

    var player1points = 0 

    for i=1;i<1000;++i{ 
     chance = Int(arc4random_uniform(1001)) 
     if chance<(ability-points) {++points} 
     else{points = points - 1} 
    } 
    if points > 0{++winner} 
} 
    println(winner) 

代碼作品直接粘貼到xcode 6.1的命令行程序項目中

由於在下一個循環中使用了變量「points」的新值,因此最內層的循環無法並行化。但是最外層的模擬運行1000000次,並計算出結果,應該是並行化的理想候選者。

所以我的問題是如何使用GCD來並行化最外面的for循環?

回答

3

「多線程迭代」可以用dispatch_apply()完成:

let outerCount = 100 // # of concurrent block iterations 
let innerCount = 10000 // # of iterations within each block 

let the_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 
dispatch_apply(UInt(outerCount), the_queue) { outerIdx -> Void in 
    for innerIdx in 1 ... innerCount { 
     // ... 
    } 
} 

(你要搞清楚外部和內部計數之間的最佳關係。)

有兩件事情要注意:

然後,它大致是這樣的:

let outerCount = 100  // # of concurrent block iterations 
let innerCount = 10000 // # of iterations within each block 

let the_queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); 

var winners = [Int](count: outerCount, repeatedValue: 0) 
winners.withUnsafeMutableBufferPointer { winnersPtr -> Void in 

    dispatch_apply(UInt(outerCount), the_queue) { outerIdx -> Void in 
     var seed = arc4random() // seed for rand_r() in this "thread" 

     for innerIdx in 1 ... innerCount { 
      var points = 0 
      var ability = 500 

      for i in 1 ... 1000 { 
       let chance = Int(rand_r(&seed) % 1001) 
       if chance < (ability-points) { ++points } 
       else {points = points - 1} 
      } 
      if points > 0 { 
       winnersPtr[Int(outerIdx)] += 1 
      } 
     } 
    } 
} 

// Add results: 
let winner = reduce(winners, 0, +) 
println(winner) 
+0

不知道,大約arc4random()!小心從多個線程修改數組 - 看到更多的問答:http://stackoverflow.com/questions/26693838/swift-process-array-in-parallel-using-gcd/26790019#26790019 – 2014-11-24 15:09:41

+0

我想我的第二個答案(不是公認的),因爲它顯式地爲數組獲取連續的內存緩衝區。 – 2014-11-24 15:10:34

+1

@NateCook:我已經有過這樣的感覺,但是找不到它。感謝您的參考和解決方案(+1),我相應地更新了答案。 – 2014-11-24 15:20:28

相關問題