Skip to content

Commit

Permalink
logger: micro-optimize time stamping
Browse files Browse the repository at this point in the history
Co-authored-by: Tony Chen <[email protected]>
Signed-off-by: Alex Aizman <[email protected]>
  • Loading branch information
alex-aizman and Nahemah1022 committed Aug 14, 2024
1 parent 9f51aed commit 455872f
Show file tree
Hide file tree
Showing 2 changed files with 47 additions and 2 deletions.
45 changes: 45 additions & 0 deletions cmn/nlog/fixedbuf.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ package nlog
import (
"io"
"os"
"time"
)

type fixed struct {
Expand Down Expand Up @@ -38,6 +39,50 @@ func (fb *fixed) writeByte(c byte) {
}
}

// "15:04:05.000000"
func (fb *fixed) writeStamp() {
now := time.Now()
hour, minute, second := now.Clock()

fb.ab(hour)
fb.buf[fb.woff] = ':'
fb.woff++

fb.ab(minute)
fb.buf[fb.woff] = ':'
fb.woff++

fb.ab(second)
fb.buf[fb.woff] = '.'
fb.woff++

fb.abcdef(now.Nanosecond() / 1000)
}

const digits = "0123456789"

func (fb *fixed) ab(d int) {
fb.buf[fb.woff] = digits[d/10]
fb.woff++

fb.buf[fb.woff] = digits[d%10]
fb.woff++
}

func (fb *fixed) abcdef(millis int) {
j := 5
for ; j >= 0 && millis > 0; j-- {
fb.buf[fb.woff+j] = digits[millis%10]
millis /= 10
}

const pad = '0'
for ; j >= 0; j-- {
fb.buf[fb.woff+j] = pad
}
fb.woff += 6
}

func (fb *fixed) flush(file *os.File) (n int, err error) {
n, err = file.Write(fb.buf[:fb.woff])
if err != nil {
Expand Down
4 changes: 2 additions & 2 deletions cmn/nlog/nlog.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,8 +275,8 @@ func formatHdr(s severity, depth int, fb *fixed) {
}
fb.writeByte(char[s])
fb.writeByte(' ')
now := time.Now()
fb.writeString(now.Format("15:04:05.000000"))

fb.writeStamp()

fb.writeByte(' ')
if _, redact := redactFnames[fn]; redact {
Expand Down

0 comments on commit 455872f

Please sign in to comment.