().UnixNano
This is the most commonly used method, but it is also the method with the greatest safety hazards.
On the surface, the maximum accuracy of the time method is to nanoseconds, but it seems that the absolute nanosecond accuracy cannot be achieved.
The test results were bad and the collision was very high.
import "time" func TestSeedNanoTime(t *) { var seeds = make(map[int64]bool) for i := 0; i < 100000; i++ { seed := ().UnixNano() seeds[seed] = true (seed) } (len(seeds)) }
This method has no collision
import "hash/maphash" func TestSeedMapHash(t *) { var seeds = make(map[int64]bool) for i := 0; i < 100000; i++ { seed := int64(new().Sum64()) seeds[seed] = true (seed) } (len(seeds)) }
This method has no collision
import ( cryptoRand "crypto/rand" mathRand "math/rand" ) func TestSeedCryptoRand(t *) { var seeds = make(map[int64]bool) for i := 0; i < 100000; i++ { var b [8]byte _, err := (b[:]) if err != nil { panic("cannot seed math/rand package with cryptographically secure random number generator") } seed := int64(.Uint64(b[:])) seeds[seed] = true (seed) } (len(seeds)) }
Mapping table
This method has no collision
func TestSeedRandomString(t *) { const alpha = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789" size := 8 var seeds = make(map[int64]bool) for i := 0; i < 100000; i++ { buf := make([]byte, size) for i := 0; i < size; i++ { buf[i] = alpha[(len(alpha))] } seed := int64(.Uint64(buf[:])) seeds[seed] = true (seed) } (len(seeds)) }
References
How to properly seed random number generator
This is the end of this article about how to generate random seeds in Go. For more related content on generating random seeds from Go, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!