Skip to content

Commit

Permalink
Use int64 nanosecnods to make atomic easier
Browse files Browse the repository at this point in the history
  • Loading branch information
boks1971 committed Sep 16, 2024
1 parent 3ddcdf8 commit 47deda5
Showing 1 changed file with 7 additions and 23 deletions.
30 changes: 7 additions & 23 deletions candidatepair.go
Original file line number Diff line number Diff line change
Expand Up @@ -32,8 +32,8 @@ type CandidatePair struct {
nominateOnBindingSuccess bool

// stats
currentRoundTripTime atomic.Pointer[time.Duration]
totalRoundTripTime atomic.Pointer[time.Duration]
currentRoundTripTime int64 // in ns
totalRoundTripTime int64 // in ns
responsesReceived uint64
}

Expand Down Expand Up @@ -111,38 +111,22 @@ func (a *Agent) sendSTUN(msg *stun.Message, local, remote Candidate) {
// UpdateRoundTripTime sets the current round time of this pair and
// accumulates total round trip time and responses received
func (p *CandidatePair) UpdateRoundTripTime(rtt time.Duration) {
p.currentRoundTripTime.Store(&rtt)

prevTotalRoundTripTime := p.totalRoundTripTime.Load()
totalRoundTripTime := rtt
if prevTotalRoundTripTime != nil {
totalRoundTripTime += *prevTotalRoundTripTime
}
p.totalRoundTripTime.CompareAndSwap(prevTotalRoundTripTime, &totalRoundTripTime)

rttNs := rtt.Nanoseconds()
atomic.StoreInt64(&p.currentRoundTripTime, rttNs)
atomic.AddInt64(&p.totalRoundTripTime, rttNs)
atomic.AddUint64(&p.responsesReceived, 1)

Check warning on line 117 in candidatepair.go

View check run for this annotation

Codecov / codecov/patch

candidatepair.go#L113-L117

Added lines #L113 - L117 were not covered by tests
}

// CurrentRoundTripTime returns the current round trip time in seconds
// https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-currentroundtriptime
func (p *CandidatePair) CurrentRoundTripTime() float64 {
crtt := p.currentRoundTripTime.Load()
if crtt != nil {
return crtt.Seconds()
}

return 0
return time.Duration(atomic.LoadInt64(&p.currentRoundTripTime)).Seconds()

Check warning on line 123 in candidatepair.go

View check run for this annotation

Codecov / codecov/patch

candidatepair.go#L122-L123

Added lines #L122 - L123 were not covered by tests
}

// TotalRoundTripTime returns the current round trip time in seconds
// https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-totalroundtriptime
func (p *CandidatePair) TotalRoundTripTime() float64 {
trtt := p.totalRoundTripTime.Load()
if trtt != nil {
return trtt.Seconds()
}

return 0
return time.Duration(atomic.LoadInt64(&p.totalRoundTripTime)).Seconds()

Check warning on line 129 in candidatepair.go

View check run for this annotation

Codecov / codecov/patch

candidatepair.go#L128-L129

Added lines #L128 - L129 were not covered by tests
}

// ResponsesReceived returns the total number of connectivity responses received
Expand Down

0 comments on commit 47deda5

Please sign in to comment.