Optimize sortPeersForPiece in allocatePendingChunks

This commit is contained in:
Matt Joiner 2021-09-10 22:12:08 +10:00
parent 0d10a1b53a
commit 016bf1b07c
1 changed files with 17 additions and 15 deletions

View File

@ -228,12 +228,14 @@ func allocatePendingChunks(p requestablePiece, peers []*requestsPeer) {
} }
}() }()
sortPeersForPiece := func(req *Request) { sortPeersForPiece := func(req *Request) {
less := func(i, j int) bool { less := func(_i, _j int) bool {
i := peersForPiece[_i]
j := peersForPiece[_j]
byHasRequest := func() multiless.Computation { byHasRequest := func() multiless.Computation {
ml := multiless.New() ml := multiless.New()
if req != nil { if req != nil {
_, iHas := peersForPiece[i].nextState.Requests[*req] _, iHas := i.nextState.Requests[*req]
_, jHas := peersForPiece[j].nextState.Requests[*req] _, jHas := j.nextState.Requests[*req]
ml = ml.Bool(jHas, iHas) ml = ml.Bool(jHas, iHas)
} }
return ml return ml
@ -245,30 +247,30 @@ func allocatePendingChunks(p requestablePiece, peers []*requestsPeer) {
// fastest known peers. // fastest known peers.
if !p.alwaysReallocate { if !p.alwaysReallocate {
ml = ml.Bool( ml = ml.Bool(
peersForPiece[j].requestablePiecesRemaining == 1, j.requestablePiecesRemaining == 1,
peersForPiece[i].requestablePiecesRemaining == 1) i.requestablePiecesRemaining == 1)
} }
if p.alwaysReallocate || peersForPiece[j].requestablePiecesRemaining == 1 { if p.alwaysReallocate || j.requestablePiecesRemaining == 1 {
ml = ml.Int( ml = ml.Int(
peersForPiece[i].requestsInPiece, i.requestsInPiece,
peersForPiece[j].requestsInPiece) j.requestsInPiece)
} else { } else {
ml = ml.AndThen(byHasRequest) ml = ml.AndThen(byHasRequest)
} }
ml = ml.Int( ml = ml.Int(
peersForPiece[i].requestablePiecesRemaining, i.requestablePiecesRemaining,
peersForPiece[j].requestablePiecesRemaining, j.requestablePiecesRemaining,
).Float64( ).Float64(
peersForPiece[j].DownloadRate, j.DownloadRate,
peersForPiece[i].DownloadRate, i.DownloadRate,
) )
ml = ml.AndThen(byHasRequest) ml = ml.AndThen(byHasRequest)
return ml.Int64( return ml.Int64(
int64(peersForPiece[j].Age), int64(peersForPiece[i].Age), int64(j.Age), int64(i.Age),
// TODO: Probably peer priority can come next // TODO: Probably peer priority can come next
).Uintptr( ).Uintptr(
peersForPiece[i].Id.Uintptr(), i.Id.Uintptr(),
peersForPiece[j].Id.Uintptr(), j.Id.Uintptr(),
).MustLess() ).MustLess()
} }
sort.Slice(peersForPiece, less) sort.Slice(peersForPiece, less)