From 455872f6702f3c468048b7815904c9640a990aca Mon Sep 17 00:00:00 2001 From: Alex Aizman Date: Wed, 14 Aug 2024 10:38:46 -0400 Subject: [PATCH] logger: micro-optimize time stamping Co-authored-by: Tony Chen Signed-off-by: Alex Aizman --- cmn/nlog/fixedbuf.go | 45 ++++++++++++++++++++++++++++++++++++++++++++ cmn/nlog/nlog.go | 4 ++-- 2 files changed, 47 insertions(+), 2 deletions(-) diff --git a/cmn/nlog/fixedbuf.go b/cmn/nlog/fixedbuf.go index 47f6c24bb1..ed08078420 100644 --- a/cmn/nlog/fixedbuf.go +++ b/cmn/nlog/fixedbuf.go @@ -8,6 +8,7 @@ package nlog import ( "io" "os" + "time" ) type fixed struct { @@ -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 { diff --git a/cmn/nlog/nlog.go b/cmn/nlog/nlog.go index 02a998ce19..608517b8d8 100644 --- a/cmn/nlog/nlog.go +++ b/cmn/nlog/nlog.go @@ -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 {