Avatar
results のコピーを無くした上で,並列処理ごとにできるだけちょうど 1個結果が返ってくるように,並列処理の本数を動的に変える実装にしてみました.(話が盛り上がってるところすみません) var targets = Array(0 ..< 1000000) var results: [Int: Int] = [:] var batch = 1 var itr = 1 while !targets.isEmpty { let next = (0 ..< batch).compactMap { _ in targets.isEmpty ? nil : targets.removeLast() } let candidates = targets.parallelCompactMap { i in find(i, results) // runs in parallel } if let (i, j) = candidates.min(by: { (i, j) in weight(i, j) }) { results[i] = j for (i1, _) in candidates where i1 != i { targets.append(i1) // redo unselected candidates. } } if candidates.count == 0 { batch *= 2 } else if candidates.count >= 2 && batch > 1 { batch /= 2 } itr += 1 } // parallelized function func find(_ i: Int, _ currentResult: [Int: Int]) -> (Int, Int)? { i % 10 == 0 ? (i, i) : nil } print(results.count) (edited)
6:40 AM
結果 1:40 かかってた処理が 1:07 ぐらいになりました🙌
🎉 3