如果您分析 ( Cmd + I
) 您的代码,您会发现大部分时间都在使用各种“复制到缓冲区”功能。当您将一个新元素附加到数组但它已用完其初始分配的空间时,会发生这种情况,因此必须将其移动到堆上具有更多内存的位置。教训的道德:堆分配很慢,但数组是不可避免的。尽可能少做几次。
尝试这个:
func convertWordToBytes2(fullW: [UInt32]) -> [[UInt8]] {
let subSize = 6
// We allocate the array only once per run since allocation is so slow
// There will only be assignment to it after
var combined48 = [UInt8](count: fullW.count * 4, repeatedValue: 0).splitBy(subSize)
var row = 0
var col = 0
for i in 0...16 {
for j in 24.stride(through: 0, by: -8) {
let value = UInt8(truncatingBitPattern: fullW[i] >> UInt32(j))
combined48[row][col] = value
col += 1
if col >= subSize {
row += 1
col = 0
}
}
}
return combined48
}
基准代码:
let testCases = (0..<1_000_000).map { _ in
(0..<17).map { _ in arc4random() }
}
testCases.forEach {
convertWordToBytes($0)
convertWordToBytes2($0)
}
结果(在我的 2012 iMac 上)
Weight Self Weight Symbol Name
9.35 s 53.2% 412.00 ms specialized convertWordToBytes([UInt32]) -> [[UInt8]]
3.28 s 18.6% 344.00 ms specialized convertWordToBytes2([UInt32]) -> [[UInt8]]
通过消除多次分配,我们已经将运行时间减少了 60%。但是每个测试用例都是独立的,这非常适合使用当今的多核 CPU 进行并行处理。修改后的循环...:
dispatch_apply(testCases.count, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0)) { i in
convertWordToBytes2(testCases[i])
}
...在我的 8 线程四核 i7 上执行时,将缩短大约 1 秒的时间:
Weight Self Weight Symbol Name
2.28 s 6.4% 0 s _dispatch_worker_thread3 0x58467
2.24 s 6.3% 0 s _dispatch_worker_thread3 0x58463
2.22 s 6.2% 0 s _dispatch_worker_thread3 0x58464
2.21 s 6.2% 0 s _dispatch_worker_thread3 0x58466
2.21 s 6.2% 0 s _dispatch_worker_thread3 0x58465
2.21 s 6.2% 0 s _dispatch_worker_thread3 0x58461
2.18 s 6.1% 0 s _dispatch_worker_thread3 0x58462
节省的时间并没有我希望的那么多。显然在访问堆内存时存在一些争用。对于更快的速度,您应该探索基于 C 的解决方案。