Commit 4cf19fb5 authored by Albert Nigmatzianov's avatar Albert Nigmatzianov Committed by Brad Fitzpatrick

log: Prevent getting time if it's unnecessary

Small performance gain:
name              old time/op    new time/op    delta
Itoa-4              95.4ns ± 4%    95.6ns ± 3%    ~     (p=0.256 n=45+46)
Println-4            480ns ± 4%     476ns ± 5%  -0.87%  (p=0.003 n=45+45)
PrintlnNoFlags-4     316ns ± 3%     299ns ± 4%  -5.38%  (p=0.000 n=42+44)

name              old alloc/op   new alloc/op   delta
Itoa-4               0.00B          0.00B         ~     (all equal)
Println-4            21.0B ± 0%     21.0B ± 0%    ~     (all equal)
PrintlnNoFlags-4     21.0B ± 0%     21.0B ± 0%    ~     (all equal)

name              old allocs/op  new allocs/op  delta
Itoa-4                0.00           0.00         ~     (all equal)
Println-4             2.00 ± 0%      2.00 ± 0%    ~     (all equal)
PrintlnNoFlags-4      2.00 ± 0%      2.00 ± 0%    ~     (all equal)

Change-Id: Idcd03609a5a437a69ffa7004a673bf0b8d22e7ad
Reviewed-on: https://go-review.googlesource.com/38056Reviewed-by: 's avatarBrad Fitzpatrick <bradfitz@golang.org>
Run-TryBot: Brad Fitzpatrick <bradfitz@golang.org>
parent d433de6e
......@@ -89,12 +89,16 @@ func itoa(buf *[]byte, i int, wid int) {
*buf = append(*buf, b[bp:]...)
}
// formatHeader writes log header to buf in following order:
// * l.prefix (if it's not blank),
// * date and/or time (if corresponding flags are provided),
// * file and line number (if corresponding flags are provided).
func (l *Logger) formatHeader(buf *[]byte, t time.Time, file string, line int) {
*buf = append(*buf, l.prefix...)
if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
if l.flag&LUTC != 0 {
t = t.UTC()
}
if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
if l.flag&Ldate != 0 {
year, month, day := t.Date()
itoa(buf, year, 4)
......@@ -143,7 +147,11 @@ func (l *Logger) formatHeader(buf *[]byte, t time.Time, file string, line int) {
// provided for generality, although at the moment on all pre-defined
// paths it will be 2.
func (l *Logger) Output(calldepth int, s string) error {
now := time.Now() // get this early.
// Get time early if we need it.
var now time.Time
if l.flag&(Ldate|Ltime|Lmicroseconds) != 0 {
now = time.Now()
}
var file string
var line int
l.mu.Lock()
......
......@@ -182,3 +182,13 @@ func BenchmarkPrintln(b *testing.B) {
l.Println(testString)
}
}
func BenchmarkPrintlnNoFlags(b *testing.B) {
const testString = "test"
var buf bytes.Buffer
l := New(&buf, "", 0)
for i := 0; i < b.N; i++ {
buf.Reset()
l.Println(testString)
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment