Commit 1e9ab9e7 authored by Dave Cheney's avatar Dave Cheney

time: add Now()/UnixNano() malloc tests

The fix for issue 4403 may include more calls to time.Now().UnixNano(). I was concerned that if this function allocated it would cause additional garbage on the heap. It turns out that it doesn't, which is a nice surprise.

Also add benchmark for Now().UnixNano()

R=bradfitz, minux.ma
CC=golang-dev
https://golang.org/cl/6849097
parent 747dda97
...@@ -10,6 +10,7 @@ import ( ...@@ -10,6 +10,7 @@ import (
"encoding/json" "encoding/json"
"fmt" "fmt"
"math/rand" "math/rand"
"runtime"
"strconv" "strconv"
"strings" "strings"
"testing" "testing"
...@@ -1037,9 +1038,47 @@ func TestParseDurationRoundTrip(t *testing.T) { ...@@ -1037,9 +1038,47 @@ func TestParseDurationRoundTrip(t *testing.T) {
} }
} }
var (
t Time
u int64
)
var mallocTest = []struct {
count int
desc string
fn func()
}{
{0, `time.Now()`, func() { t = Now() }},
{0, `time.Now().UnixNano()`, func() { u = Now().UnixNano() }},
}
func TestCountMallocs(t *testing.T) {
defer runtime.GOMAXPROCS(runtime.GOMAXPROCS(1))
for _, mt := range mallocTest {
const N = 100
memstats := new(runtime.MemStats)
runtime.ReadMemStats(memstats)
mallocs := 0 - memstats.Mallocs
for i := 0; i < N; i++ {
mt.fn()
}
runtime.ReadMemStats(memstats)
mallocs += memstats.Mallocs
if mallocs/N > uint64(mt.count) {
t.Errorf("%s: expected %d mallocs, got %d", mt.desc, mt.count, mallocs/N)
}
}
}
func BenchmarkNow(b *testing.B) { func BenchmarkNow(b *testing.B) {
for i := 0; i < b.N; i++ { for i := 0; i < b.N; i++ {
Now() t = Now()
}
}
func BenchmarkNowUnixNano(b *testing.B) {
for i := 0; i < b.N; i++ {
u = Now().UnixNano()
} }
} }
......
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