jped - 6 months ago 24

Swift Question

So, I've written some code in Swift 3 as a CLI to practice using Grand Central Dispatch.

The idea is, there are three arrays each filled with 100000000 values. I then have a function to sum up all the numbers of the array and print it out. And then there are two more functions to time the sum of these arrays. One to run the sum function three times on each array. The other runs the sum function on each array on its own async (thread?, dispatch?, not sure what word to use here.)

Here's the code:

`import Foundation`

func sum(array a: [Int]) {

var suma = 0

for n in a {

suma += n

}

print(suma)

}

func gcd(a: [Int], b: [Int], c: [Int]) {

let queue = DispatchQueue(label: "com.apple.queue")

let group = DispatchGroup()

let methodStart = Date()

queue.async(group: group, execute: {

sum(array: a)

})

queue.async(group: group, execute: {

sum(array: b)

})

queue.async(group: group, execute: {

sum(array: c)

})

group.notify(queue: .main) {

let methodFinish = Date()

let executionTime = methodFinish.timeIntervalSince(methodStart)

print("GCD Exectuion Time: \(executionTime)")

}

}

func non_gcd(a: [Int], b: [Int], c: [Int]) {

let methodStart = Date()

sum(array: a)

sum(array: b)

sum(array: c)

let methodFinish = Date()

let executionTime = methodFinish.timeIntervalSince(methodStart)

print("Non_GCD Exectuion Time: \(executionTime)")

}

var a = [Int]()

var b = [Int]()

var c = [Int]()

// fill each array with 0 to 1 mil - 1

for i in 0..<100000000 {

a.append(i)

b.append(i+1)

c.append(i+2)

}

non_gcd(a: a, b: b, c: c)

gcd(a: a, b: b, c: c)

dispatchMain()

And here's the output where you can see it runs about the same time:

`4999999950000000`

5000000050000000

5000000150000000

Non_GCD Execution Time: 1.15053302049637

4999999950000000

5000000050000000

5000000150000000

GCD Execution Time: 1.16769099235535

I'm curious as to why it's almost the same time?

I thought concurrent programming made things faster. I think I'm missing something important.

Answer

You are creating a serial queue so your "gcd" code doesn't take any advantage of multi-threading.

Change:

```
let queue = DispatchQueue(label: "com.apple.queue")
```

to:

```
let queue = DispatchQueue(label: "com.apple.queue", attributes: .concurrent)
```

and then run your tests again. You should see an improvement since the three calls to `async`

can now take advantage of multi-threading.