Skip to content

Commit

Permalink
reduce heap allocation #13 (#365)
Browse files Browse the repository at this point in the history
Summary:
Pull Request resolved: #365

Avoid recreating error group, context and a cancel func by replacing them with a channel.

Reviewed By: abulimov

Differential Revision: D58472316

fbshipit-source-id: 64d6df51ba63df8700b8bf7d17586c38ed7d90b7
  • Loading branch information
leoleovich authored and facebook-github-bot committed Jun 14, 2024
1 parent 9b8c0c3 commit 33e1d70
Showing 1 changed file with 20 additions and 10 deletions.
30 changes: 20 additions & 10 deletions ptp/sptp/client/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import (
"time"

log "github.com/sirupsen/logrus"
"golang.org/x/sync/errgroup"

ptp "github.com/facebook/time/ptp/protocol"
)
Expand Down Expand Up @@ -229,18 +228,20 @@ func (c *Client) handleDelayReq(clockID ptp.ClockIdentity, ts time.Time) error {
func (c *Client) RunOnce(ctx context.Context, timeout time.Duration) *RunResult {
ctx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
eg, ctx := errgroup.WithContext(ctx)
errchan := make(chan error)

result := RunResult{
Server: c.server,
}
c.m.cleanup()

eg.Go(func() error {
go func() {
defer close(errchan)
// ask for delay
seq, hwts, err := c.SendEventMsg(c.delayRequest)
if err != nil {
return err
errchan <- err
return
}
c.m.addT3(seq, hwts)
log.Debugf("[%s] client -> %s (seq=%d, our T3=%v)", c.server, ptp.MessageDelayReq, seq, hwts)
Expand All @@ -249,24 +250,33 @@ func (c *Client) RunOnce(ctx context.Context, timeout time.Duration) *RunResult
for {
select {
case <-ctx.Done():
log.Debugf("[%s] cancelled main loop", c.server)
return ctx.Err()
log.Debugf("[%s] cancelled routine", c.server)
errchan <- ctx.Err()
return
case <-c.inChan:
latest, err := c.m.latest()
if err != nil {
log.Debugf("[%s] getting latest measurement: %v", c.server, err)
if !errors.Is(err, errNotEnoughData) {
return err
errchan <- err
return
}
} else {
log.Debugf("[%s] latest measurement: %+v", c.server, latest)
result.Measurement = latest
return nil
errchan <- nil
return
}
}
}
})
result.Error = eg.Wait()
}()

select {
case err := <-errchan:
result.Error = err
case <-ctx.Done():
result.Error = ctx.Err()
}

return &result
}

0 comments on commit 33e1d70

Please sign in to comment.