Skip to content

Commit

Permalink
Find fastest possible read time for fakeNonblockingReadWaitDuration
Browse files Browse the repository at this point in the history
The first 5 fake non-blocking reads are limited to 1 byte. This should
ensure that there is a measurement of a read where bytes are already
waiting in Go or the OS's read buffer.
  • Loading branch information
jackc committed Feb 1, 2023
1 parent f46d356 commit 6bc327b
Showing 1 changed file with 8 additions and 0 deletions.
8 changes: 8 additions & 0 deletions internal/nbconn/nbconn.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,7 @@ type NetConn struct {
readDeadlineLock sync.Mutex
readDeadline time.Time
readNonblocking bool
fakeNonBlockingShortReadCount int
fakeNonblockingReadWaitDuration time.Duration

writeDeadlineLock sync.Mutex
Expand Down Expand Up @@ -416,6 +417,13 @@ func (c *NetConn) fakeNonblockingRead(b []byte) (n int, err error) {
c.readDeadlineLock.Lock()
defer c.readDeadlineLock.Unlock()

// The first 5 reads only read 1 byte at a time. This should give us 4 chances to read when we are sure the bytes are
// already in Go or the OS's receive buffer.
if c.fakeNonBlockingShortReadCount < 5 && len(b) > 0 {
b = b[:1]
c.fakeNonBlockingShortReadCount++
}

startTime := time.Now()
deadline := startTime.Add(c.fakeNonblockingReadWaitDuration)
if c.readDeadline.IsZero() || deadline.Before(c.readDeadline) {
Expand Down

0 comments on commit 6bc327b

Please sign in to comment.