当在 iOS 上运行的 Swift 中的数组上运行 for 循环时,我想利用整个 CPU,因为我觉得这在理论上应该可以加快计算速度。然而我的结果是相反的,在一个DispatchQueue
而不是多个DispatchQueue
s 上运行所有东西,实际上执行得更快。我将提供一个示例,并想知道为什么单线程方法更快,如果可能的话,我仍然可以通过正确利用多个 cpu 内核来降低计算所需的时间?
对于那些只想查看我的意图代码的人可以跳过,因为下一节仅详细说明我的意图和方法。
我在示例中提供的意图:
我正在确定地图上的一条线(汽车行驶的轨迹,每秒的纬度和经度)是否在某个预定义的区域内,地图上的多边形(整个区域的纬度和经度)。为此,我有一个函数可以计算单个点是否在多边形内。我正在使用 for 循环来遍历汽车行驶轨迹中的每个位置,并使用该函数检查该点是否在多边形内。如果每个跟踪的位置都在多边形内,则整个跟踪的汽车行程都发生在所述区域内。
我将 iPhone X 用于开发目的,并利用整个 CPU 来加速计算。
我的做法:
在提供的示例中,我有 3 个变体,导致计算所需的以下时间(以秒为单位):
Time elapsed for single thread variant: 6.490409970283508 s.
Time elapsed for multi thread v1 variant: 24.076722025871277 s.
Time elapsed for multi thread v2 variant: 23.922222018241882 s.
第一种方法是最简单的,即不使用多个DispatchQueue
.
第二种方法利用DispatchQueue.concurrentPerform(iterations: Int)
. 我觉得这可能是满足我需求的最佳解决方案,因为它已经实施并且似乎是为我的确切目的而设计的。
DispatchQueue
第三种方法是我自己的,它根据操作系统报告的活动 CPU 内核的数量将阵列的大致相等的部分安排到在 s 上运行的 for 循环。
我也尝试过使用inout
参数(通过引用调用)的变体,但无济于事。时间保持不变,因此我没有提供更多代码来混淆问题。
我也知道,一旦我发现一个不在多边形内的点,我就可以返回该函数,但这不是这个问题的一部分。
我的代码:
/**
Function that calculates wether or not a
single coordinate is within a polygon described
as a pointlist.
This function is used by all others to do the work.
*/
private static func contains(coordinate: CLLocationCoordinate2D, with pointList: [CLLocationCoordinate2D]) -> Bool {
var isContained = false
var j = pointList.count - 1
let lat = coordinate.latitude
let lon = coordinate.longitude
for i in 0 ..< pointList.count {
if (pointList[i].latitude > lat) != (pointList[j].latitude > lat) &&
(lon < (pointList[j].longitude - pointList[i].longitude) * (lat - pointList[i].latitude) / (pointList[j].latitude - pointList[i].latitude) + pointList[i].longitude) {
isContained.toggle()
}
j = i
}
return isContained
}
///Runs all three variants as are described in the question
static func testAllVariants(coordinates: [CLLocationCoordinate2D], areInside pointList: [CLLocationCoordinate2D]) {
var startTime = CFAbsoluteTimeGetCurrent()
var bool = contains_singleThread(coordinates: coordinates, with: pointList)
var timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("Time elapsed for single thread variant: \(timeElapsed) s.")
startTime = CFAbsoluteTimeGetCurrent()
bool = contains_multiThread_v1(coordinates: coordinates, with: pointList)
timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("Time elapsed for multi thread v1 variant: \(timeElapsed) s.")
startTime = CFAbsoluteTimeGetCurrent()
bool = contains_multiThread_v2(coordinates: coordinates, with: pointList)
timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
print("Time elapsed for multi thread v2 variant: \(timeElapsed) s.")
}
private static func contains_singleThread(coordinates: [CLLocationCoordinate2D], with pointList: [CLLocationCoordinate2D]) -> Bool {
var bContainsAllPoints = true
for coordinate in coordinates {
if !contains(coordinate: coordinate, with: pointList) {
bContainsAllPoints = false
}
}
return bContainsAllPoints
}
private static func contains_multiThread_v1(coordinates: [CLLocationCoordinate2D], with pointList: [CLLocationCoordinate2D]) -> Bool {
let numOfCoordinates = coordinates.count
var booleanArray = Array(repeating: true, count: numOfCoordinates)
DispatchQueue.concurrentPerform(iterations: numOfCoordinates) { (index) in
if !contains(coordinate: coordinates[index], with: pointList) {
booleanArray[index] = false
}
}
return !booleanArray.contains(false)
}
private static func contains_multiThread_v2(coordinates: [CLLocationCoordinate2D], with pointList: [CLLocationCoordinate2D]) -> Bool {
let numOfCoordinates = coordinates.count
let coreCount = ProcessInfo().activeProcessorCount
func chunk<T>(array: [T], into size: Int) -> [[T]] {
return stride(from: 0, to: array.count, by: size).map {
Array(array[$0 ..< Swift.min($0 + size, array.count)])
}
}
let segments = chunk(array: coordinates, into: numOfCoordinates/coreCount)
let dg = DispatchGroup()
for i in 0..<segments.count {
dg.enter()
}
var booleanArray = Array(repeating: true, count: segments.count)
for (index, segment) in segments.enumerated() {
DispatchQueue.global(qos: .userInitiated).async {
for coordinate in segment {
if !contains(coordinate: coordinate, with: pointList) {
booleanArray[index] = false
}
}
dg.leave()
}
}
dg.wait()
return !booleanArray.contains(false)
}
示例数据
我已经为那些希望有数据运行测试的人上传了两个 json 文件。这是导致我记录时间的相同输入。
追踪到的乘车:链接到 json 文件 区域/区域:链接到 json 文件