gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 00:49:59 28 4
gpt4 key购买 nike

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

想法是,有三个数组,每个数组都填充了 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”代码不会利用多线程。

改变:

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

到:

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

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

关于swift - 为什么使用 GCD 的 Swift CLI 代码与不使用并发的代码运行速度相同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40196809/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com