I try to speed-up some function by make it multithread.
And I have very disappointing results.
First — „flat” version, processor get hot:
var correctionSubspaces : [[Vertex]] = []
for correction in corrections { // evey correction
var vertexLayers: [Vertex] = [] // subgrid for one correction
for coordinates in newGridCoordinates { // every new grid position
try Task.checkCancellation()
let vertexWithStrength = try await Self.vertexStrength(for: correction,
in: corners,
on: coordinates)
vertexLayers.append(vertexWithStrength)
}
correctionSubspaces.append(vertexLayers)
}
works nice, but for some heavy stuff it took:
axes: 4, corners: 16, corrections: 4
✅testCountGrid() 1296 elements in 56.065s
Second version, first with TaskGroup was surprising:
var correctionSubspaces : [[Vertex]] = [] //
for correction in corrections { // every correction
let correctionSubspace = try await withThrowingTaskGroup(of: Vertex.self,
returning: [Vertex].self) { verticesTasks in
newGridCoordinates.forEach { coordinates in
verticesTasks.addTask {
return try await Self.vertexStrength(for: correction,
in: corners,
on: coordinates)
}
}
var vertexLayer: [Vertex] = []
for try await vertex in verticesTasks {
vertexLayer.append(vertex)
}
return vertexLayer
}
correctionSubspaces.append(correctionSubspace)
}
almost 140% SLOWER, processor red-hot too. In debug view I can see a lot of threads works. Sweat.
axes: 4, corners: 16, corrections: 4
✅testCountGrid() 1296 elements in 78.229451s.
So, I wrote third version; newGridCoordinates
has many (1296 this case) elements, corrections
just one to five...
let correctionSubspaces = try await withThrowingTaskGroup(of: [Vertex].self,
returning: [[Vertex]].self)
{ correctionTasks in
corrections.forEach { correction in
correctionTasks.addTask {
var vertexLayers:[Vertex] = []
for coordinates in newGridCoordinates { // every new grid position
let vertexWithStrength = try await Self.vertexStrength(for: correction,
in: corners,
on: coordinates)
vertexLayers.append(vertexWithStrength)
}
return vertexLayers
}
}
var subspace :[[Vertex]] = []
for try await layer in correctionTasks {
subspace.append(layer)
}
return subspace
}
Surprise, surprise:
axes: 4, corners: 16, corrections: 4
✅testCountGrid() 1296 elements in 46.218377s
but only 80% time of than „flat” version.
Do I do something completely wrong, or this is a normal behaviour?