为什么我的 Swift 使用 GCD 运行 的 CLI 代码与不使用并发的代码速度相同?

Why does my Swift CLI code that uses GCD run at the same speed as the code that doesn't use concurrency?

因此,我在 Swift 3 中编写了一些代码作为 CLI 来练习使用 Grand Central Dispatch。

想法是,有三个数组,每个数组填充了 100000000 个值。然后我有一个函数来总结数组的所有数字并将其打印出来。然后还有两个函数来计算这些数组的总和。一到 运行 每个数组上的求和函数三次。另一个 运行 是每个数组上自己异步的求和函数(线程?,分派?,不确定在这里使用什么词。) 这是代码:

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()

这里是输出,您可以在 运行 大约同时看到它:

4999999950000000
5000000050000000
5000000150000000
Non_GCD Execution Time: 1.15053302049637
4999999950000000
5000000050000000
5000000150000000
GCD Execution Time: 1.16769099235535

我很好奇为什么几乎是同一时间? 我认为并发编程使事情变得更快。我想我错过了一些重要的东西。

您正在创建一个串行队列,因此您的 "gcd" 代码没有利用多线程的任何优势。

变化:

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

至:

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

然后 运行 再次测试。您应该会看到改进,因为对 async 的三个调用现在可以利用多线程。