I'm trying to bow my head around how to use the GCD to parallelize and speed up Monte Carlo simulations. Most / all simple examples are provided for Objective-C, and I really need a simple example for Swift, since Swift is my first βrealβ programming language.
The smallest working version of Monte Carlo simulation in Swift will be something like this:
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)
The code works directly inserted into the project of the command line program in xcode 6.1
The innermost loop cannot be parallelized because the new value of the point variable is used in the next loop. But the outermost ones just run the innermost simulation 1,000,000 times and count the results and should be the perfect candidate for parallelization.
So my question is how to use GCD to parallelize the outermost loop?
source share