]> Cypherpunks repositories - gostls13.git/commitdiff
time: add Now()/UnixNano() malloc tests
authorDave Cheney <dave@cheney.net>
Sun, 25 Nov 2012 00:29:06 +0000 (11:29 +1100)
committerDave Cheney <dave@cheney.net>
Sun, 25 Nov 2012 00:29:06 +0000 (11:29 +1100)
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

src/pkg/time/time_test.go

index 9888d0d9c190347d2d353dadbf8ad0fef2b87a4a..8602fcef8b2f70aa017f483aed27389db79643a0 100644 (file)
@@ -10,6 +10,7 @@ import (
        "encoding/json"
        "fmt"
        "math/rand"
+       "runtime"
        "strconv"
        "strings"
        "testing"
@@ -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) {
        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()
        }
 }