concurrentMap 实现如下:
extension Array {
func concurrentMap<T>(_ mapper: (Element) -> T) -> [T] {
if self.count == 0 {
return []
}
let q = DispatchQueue(label: "dispatch sync queue")
var result = Array<T?>(repeating: nil, count: self.count)
DispatchQueue.concurrentPerform(iterations: self.count) { (idx) in
let element = self[idx]
let transformed = mapper(element)
q.sync {
result[idx] = transformed
}
}
return result.map{ $0! }
}
}
测试用例如下:
let a = Array(0..<60000)
let startTime = mach_absolute_time()
a.map{ $0 / 2000 }
let midTime = mach_absolute_time()
a.concurrentMap{ $0 / 2000 }
let endTime = mach_absolute_time()
结果:
There are 60000 elements.
STL map consumes: 8144985
concurrentMap consumes: 567991454
1
66450146 2019-01-11 22:19:44 +08:00
因为 overhead 比计算花的时间更长啊……而且这也不是 STL ……
把 map 里面换成 `_ in sleep(1)` 就是 concurrent 更快了 一个程序员碰到了一个问题,他决定用多线程来解决。现在他有两个了问题 |