Skip to content

Commit

Permalink
chore: avoid calling expensive time.Now if metrics are not enabled
Browse files Browse the repository at this point in the history
  • Loading branch information
vgonkivs committed Feb 1, 2024
1 parent 3e7e45e commit b3f5719
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 4 deletions.
19 changes: 17 additions & 2 deletions sync/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type metrics struct {
syncStartedTs time.Time

requestRangeTimeHist metric.Float64Histogram
requestRangeStartTs time.Time

blockTime metric.Float64Histogram
prevHeader time.Time
Expand Down Expand Up @@ -165,9 +166,9 @@ func (m *metrics) subjectiveInitialization(ctx context.Context) {
})
}

func (m *metrics) getRangeRequestTime(ctx context.Context, duration time.Duration, amount int, failed bool) {
func (m *metrics) updateGetRangeRequestInfo(ctx context.Context, amount int, failed bool) {
m.observe(ctx, func(ctx context.Context) {
m.requestRangeTimeHist.Record(ctx, duration.Seconds(),
m.requestRangeTimeHist.Record(ctx, time.Since(m.requestRangeStartTs).Seconds(),
metric.WithAttributes(
attribute.Int("headers amount", amount),
attribute.Bool("request failed", failed),
Expand All @@ -185,6 +186,20 @@ func (m *metrics) newSubjectiveHead(ctx context.Context, height uint64, timestam
})
}

func (m *metrics) rangeRequestStart() {
if m == nil {
return
}
m.requestRangeStartTs = time.Now()
}

func (m *metrics) rangeRequestStop() {
if m == nil {
return
}
m.requestRangeStartTs = time.Time{}
}

func (m *metrics) observe(ctx context.Context, observeFn func(context.Context)) {
if m == nil {
return
Expand Down
5 changes: 3 additions & 2 deletions sync/sync.go
Original file line number Diff line number Diff line change
Expand Up @@ -316,10 +316,11 @@ func (s *Syncer[H]) requestHeaders(
size = amount
}

now := time.Now()
to := fromHead.Height() + size + 1
s.metrics.rangeRequestStart()
headers, err := s.getter.GetRangeByHeight(ctx, fromHead, to)
s.metrics.getRangeRequestTime(s.ctx, time.Since(now), int(size)/100, err != nil)
s.metrics.updateGetRangeRequestInfo(s.ctx, int(size)/100, err != nil)
s.metrics.rangeRequestStop()
if err != nil {
return err
}
Expand Down

0 comments on commit b3f5719

Please sign in to comment.