2
因此,我在Swift 3中编写了一些代码作为使用Grand Central Dispatch的CLI练习。为什么使用GCD的Swift CLI代码与不使用并发的代码运行速度相同?
这个想法是,有三个数组,每个数组都填充有100000000个值。然后我有一个函数来总结数组的所有数字并将其打印出来。然后还有两个函数来计算这些数组的总和。一个在每个阵列上运行求和函数三次。其他运行在每个阵列上的SUM函数自身异步(线程?调度?不知道这里用什么词) 下面的代码:
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代码现在运行两次! – jped