gpt4 book ai didi

ios - 我可以控制并发执行的并行度吗?

转载 作者:行者123 更新时间:2023-11-30 10:53:01 25 4
gpt4 key购买 nike

我编写了一个使用 DispatchQueue.concurrentPerform(iterations:execute:) 的例程,并将其用于多线程编程。

当我错误地将queue.sync的无意义迭代放入其他函数中时,我很惊讶地发现性能更好。此次迭代让并发执行在 A12X Bionic 中使用更多核心。

当然Apple's document说,

Many factors affect the number of tasks executed by the concurrent queues, including the number of available cores, the amount of work being done by other processes, and the number and priority of tasks in other serial dispatch queues.

我想通过合理的方式获得更好的性能。如何控制concurrentPerform的并行度?

将队列的 QoS 更改为 .userInitiated 没有效果。

谢谢。

最佳答案

我们来试试吧!下一个示例以两种不同的方式执行简单的作业,首先在 .default .concurrent 队列上异步分派(dispatch)所有作业,然后使用 DispatchQueue.concurrentPerform。

DispatchQueue.concurrentPerform 是一个非常好的且易于使用的构造。

import Foundation
import PlaygroundSupport

PlaygroundPage.current.needsIndefiniteExecution = true

let q = DispatchQueue(label: "internal", qos: .utility, attributes: .concurrent)
func job()->String {
var sum = 0
for i in 1...1000 {
let r = Int.random(in: 0..<i)
sum += r
}
let res = sum.description
return res
}

func asyncFoo(on: DispatchQueue, id: Int, completition: @escaping (_ id: Int, _ result: String)->()) {

on.async {
let res = job()
completition(id, res)
}
}

let group = DispatchGroup()

var start = Date()

for i in 0..<10 {
group.enter() // enter the group before the task starts
asyncFoo(on: q, id: i) { (id, result) in
print("id:", id, i, result)
group.leave() // leave the group when task finished
}
}
group.notify(queue: .main) {
var stop = Date()
print("all asynchronously dispatched done in", stop.timeIntervalSince(start), "seconds")
let task: (Int)->() = { i in
let res = job()
print("id:", i, res)
}
print("continue again ...")
start = Date()
DispatchQueue.concurrentPerform(iterations: 10, execute: task)
stop = Date()
print("all .concurrentPerform done in", stop.timeIntervalSince(start), "seconds")
PlaygroundPage.current.finishExecution()
}
print("continue execution ...")

结果怎么样?

continue execution ...
id: 7 7 251189
id: 2 2 252628
id: 8 8 248525
id: 5 5 248212
id: 0 0 254412
id: 3 3 255094
id: 6 6 260566
id: 1 1 242460
id: 9 9 247018
id: 4 4 246296
all asynchronously dispatched done in 0.10741996765136719 seconds
continue again ...
id: 2 248549
id: 3 245366
id: 7 242868
id: 8 252247
id: 0 250905
id: 4 249909
id: 6 247525
id: 9 246204
id: 1 253908
id: 5 249081
all .concurrentPerform done in 0.05399894714355469 seconds

如果可用,我更喜欢使用 .concurrentPerform,但这实际上取决于...没有 API 可以更改 .concurrentPerform 上的任何内容,但很可能它将是您的最佳执行者。

关于ios - 我可以控制并发执行的并行度吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54267051/

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