Skip to content
/ mt Public

Mersenne Twister; Pseudo Random Number Generator, Implemented by Golang

License

Notifications You must be signed in to change notification settings

goark/mt

Repository files navigation

spiegel-im-spiegel/mt -- Mersenne Twister; Pseudo Random Number Generator, Implemented by Golang

check vulns lint status GitHub license GitHub release

This package is "Mersenne Twister" algorithm, implemented by pure Go.

  • Compatible with math/rand standard package.
  • Concurrency-safe (if it uses mt.PRNG type)

Usage

Usage with math/rand Standard Package (not concurrency-safe)

import (
    "fmt"
    "math/rand"

    "github.com/spiegel-im-spiegel/mt/mt19937"
)

fmt.Println(rand.New(mt19937.New(19650218)).Uint64())
//Output:
//13735441942630277712

Usage of mt.PRNG type (concurrency-safe version)

import (
    "fmt"

    "github.com/spiegel-im-spiegel/mt"
    "github.com/spiegel-im-spiegel/mt/mt19937"
)

fmt.Println(mt.New(mt19937.New(19650218)).Uint64())
//Output:
//13735441942630277712

Use io.Reader interface

package main

import (
    "fmt"
    "sync"

    "github.com/spiegel-im-spiegel/mt"
    "github.com/spiegel-im-spiegel/mt/mt19937"
)

func main() {
    prng := mt.New(mt19937.New(19650218))
    wg := sync.WaitGroup{}
    for i := 0; i < 1000; i++ {
        wg.Add(1)
        go func() {
            defer wg.Done()
            r := prng.NewReader()
            for i := 0; i < 10000; i++ {
                buf := [8]byte{}
                _, err := r.Read(buf[:])
                if err != nil {
                    return
                }
            }
        }()
    }
    wg.Wait()
}

Benchmark Test

$ go test -bench Random -benchmem ./benchmark
goos: linux
goarch: amd64
pkg: github.com/spiegel-im-spiegel/mt/benchmark
BenchmarkRandomALFG-4            	1000000000	         0.0466 ns/op	       0 B/op	       0 allocs/op
BenchmarkRandomMT19917-4         	1000000000	         0.0649 ns/op	       0 B/op	       0 allocs/op
BenchmarkRandomALFGRand-4        	1000000000	         0.0720 ns/op	       0 B/op	       0 allocs/op
BenchmarkRandomMT19917Rand-4     	1000000000	         0.0862 ns/op	       0 B/op	       0 allocs/op
BenchmarkRandomALFGLocked-4      	1000000000	         0.172 ns/op	       0 B/op	       0 allocs/op
BenchmarkRandomMT19917Locked-4   	1000000000	         0.192 ns/op	       0 B/op	       0 allocs/op
PASS
ok  	github.com/spiegel-im-spiegel/mt/benchmark	6.895s

License

This package is licensed under MIT license.