this反射器包中,它提到了一个不稳定的值用作名称后缀。它是以12345为模的纳秒数。这是否有意义,或者它只是伪随机的同义词,所以人类不解释它?

// reflectorDisambiguator is used to disambiguate started reflectors.
// initialized to an unstable value to ensure meaning isn't attributed to the suffix.
var reflectorDisambiguator = int64(time.Now().UnixNano() % 12345)

“不稳定”一词是什么让我不确定。在这种情况下是什么意思?

与另一种在12345以下获得随机数的方法相比,这样做有优势吗?

最佳答案

含义似乎很清楚:



后缀行为不应是确定性的,因为您不应依赖于特定的实现行为。

例如,Go map 发生了类似情况:



类似的担忧导致提出了一项提案,该提案尚未实现,以确保不稳定排序的顺序不稳定:



以下是比较time.Now()rand.Intn()的基准:

package main

import "testing"

import (
    rand "math/rand"
    "time"
)

// https://github.com/kubernetes/client-go/blob/79cb21f5b3b1dd8f8b23bd3f79925b4fda4e2562/tools/cache/reflector.go#L100
var reflectorDisambiguator = int64(time.Now().UnixNano() % 12345)

func BenchmarkTimeNow(b *testing.B) {
    for N := 0; N < b.N; N++ {
        reflectorDisambiguator = int64(time.Now().UnixNano() % 12345)
    }
}

// rand.Intn()
func init() {
    rand.Seed(time.Now().UnixNano())
    reflectorDisambiguator = int64(rand.Intn(12345))
}

func BenchmarkRandIntn(b *testing.B) {
    for N := 0; N < b.N; N++ {
        rand.Seed(time.Now().UnixNano())
        reflectorDisambiguator = int64(rand.Intn(12345))
    }
}

输出:
$ go test disambiguator_test.go -bench=.
goos: linux
goarch: amd64
BenchmarkTimeNow-4      20000000            67.5 ns/op
BenchmarkRandIntn-4       100000         11941 ns/op
$

09-19 00:43