🐹

rand.Float64() は遅くない

に公開

きっかけ

Go で乱数を使うとき rand.Float64() で悩むことはないですか?

よく言われる話として:

  1. rand.Float64() は内部で mutex を使っている
  2. 複数の goroutine から同時に呼ぶと、他の goroutine の計算完了を待つ必要がある
  3. したがって高並行環境では避けるべき

ゲームサーバーなど、リクエストごとに乱数判定が必要な高 QPS システムでは、この「mutex ボトルネック」は深刻な問題になりうる。

疑問

  1. rand.Float64() は本当に mutex を使っているのか?
  2. Go のバージョンによって実装は変わったのか?
  3. math/rand/v2 では mutex を使わないなら、何で同期しているのか?
  4. 「per-OS-thread」とは何か? goroutine とどう関係するのか?
  5. 「Per-Goroutine で乱数生成器を持つ」にはどうすればよいか?
  6. 実際にベンチマークで差が出るのか?

検証

一次情報の調査

証拠 1: 公式ドキュメント(pkg.go.dev/math/rand)

Top-level functions, such as Float64 and Int,
are safe for concurrent use by multiple goroutines.

トップレベル関数は goroutine-safe であることが明記されている。ただし「安全」と「高速」は別の話だ。

証拠 2: Go 1.19 以前のソースコード

// Go 1.19 以前の実装
var globalRand = New(&lockedSource{src: NewSource(1)})

type lockedSource struct {
    lk  sync.Mutex  // ← ここに mutex がある
    src Source64
}

func (r *lockedSource) Int63() (n int64) {
    r.lk.Lock()
    n = r.src.Int63()
    r.lk.Unlock()
    return
}

Go 1.19 以前では確かにグローバル mutex が存在していた。

証拠 3: Go 公式ブログ「Evolving the Go Standard Library with math/rand/v2」

Having eliminated repeatability of the global output stream, Go 1.20 was also able to make the global generator scale better in programs that don't call rand.Seed, replacing the Go 1 generator with a very cheap per-thread wyrand generator already used inside the Go runtime. This removed the global mutex and made the top-level functions scale much better.

Go 1.20 でグローバル mutex は削除された。

証拠 4: math/rand/v2 のソースコード

// math/rand/v2/rand.go
type runtimeSource struct{}

func (runtimeSource) Uint64() uint64 {
    return runtime_rand()  // ランタイムの per-thread 実装を直接呼ぶ
}

var globalRand = &Rand{src: runtimeSource{}}

func Float64() float64 { return globalRand.Float64() }

math/rand/v2 には sync.Mutex が存在しない。

証拠 5: GitHub Issue #61716(math/rand/v2 の提案)

Use a per-OS-thread ChaCha8 for the global random generator

per-OS-thread(各 OS スレッドごと)に独立した乱数生成器を持つ設計になっている。

疑問への回答

Q1: mutex を使わないなら、何で同期しているのか?

答えは「同期していない」。そもそも同期が不要な設計になっている。

math/rand/v2 の runtime_rand() は、Go ランタイム内部の per-P(Processor ごと)の乱数状態を使う。各 P は独立した乱数生成器の状態を持っているため、異なる P で動く goroutine 同士が同じメモリにアクセスすることがない。

// runtime/rand.go(概念的な実装)
func rand() uint64 {
    mp := getg().m.p  // 現在の goroutine が動いている P を取得
    // P ごとに独立した乱数状態を使う → 他の P とメモリを共有しない
    return mp.randState.next()
}

mutex が不要な理由:

  • 共有状態がない → ロックする対象がそもそも存在しない
  • 各 P が独自の乱数状態を持つ → 他の P の状態に触らない
  • goroutine は常に何らかの P 上で動く → その P の状態を使う

Q2: 「per-OS-thread」「per-P」とは何か?

Go のスケジューラを理解するには、G, M, P の 3 つの概念が重要だ。

記号 名前 説明
G Goroutine ユーザーが go func() で作る軽量スレッド
M Machine OS スレッド(カーネルスレッド)
P Processor 論理プロセッサ。G を M 上で実行するためのコンテキスト

GMP diagram

重要なポイント:

  1. P の数は GOMAXPROCS で決まる(デフォルトは CPU コア数)
  2. 各 P は独自の乱数状態を持つ
  3. goroutine は常に何らかの P 上で実行される
  4. 同じ P 上で動く goroutine は順番に実行される(同時には動かない)

したがって:

  • 同じ P 上の goroutine → 順番に実行されるので競合しない
  • 異なる P 上の goroutine → 別々の乱数状態を使うので競合しない

どちらにしても mutex は不要になる。

Q3: Per-Goroutine で乱数生成器を持つにはどうすればよいか?

math/rand/v2 では、自前の *rand.Rand を作成できる:

package main

import (
    "math/rand/v2"
)

// パターン1: 構造体に持たせる(推奨)
type Worker struct {
    rng *rand.Rand
}

func NewWorker() *Worker {
    // PCG (Permuted Congruential Generator) を使用
    return &Worker{
        rng: rand.New(rand.NewPCG(rand.Uint64(), rand.Uint64())),
    }
}

// テスト用(seed 固定で再現性確保)
func NewWorkerWithSeed(s1, s2 uint64) *Worker {
    return &Worker{
        rng: rand.New(rand.NewPCG(s1, s2)),
    }
}

func (w *Worker) Float64() float64 {
    return w.rng.Float64()
}

func (w *Worker) IntN(n int) int {
    return w.rng.IntN(n)
}

使用例:

func main() {
    // 各 goroutine が独自の乱数生成器を持つ
    for i := 0; i < 10; i++ {
        go func() {
            w := NewWorker()
            for j := 0; j < 1000; j++ {
                _ = w.Float64()
            }
        }()
    }
}

利点:

  • 完全に独立した乱数ストリーム
  • テスト時に seed を固定すれば再現性を確保できる
  • キャッシュ局所性が向上する可能性

注意点として、*rand.Rand は goroutine-safe ではない。1 つの *rand.Rand を複数の goroutine で共有してはいけない。

検証コード

実際にベンチマークを取って確認する。

// benchmark_rand_test.go
package main

import (
    "math/rand"
    randv2 "math/rand/v2"
    "sync"
    "testing"
)

// lockedSource は Go 1.19 以前の挙動を再現するための mutex 付き Source
type lockedSource struct {
    mu  sync.Mutex
    src rand.Source
}

func (s *lockedSource) Int63() int64 {
    s.mu.Lock()
    n := s.src.Int63()
    s.mu.Unlock()
    return n
}

func (s *lockedSource) Seed(seed int64) {
    s.mu.Lock()
    s.src.Seed(seed)
    s.mu.Unlock()
}

// パターン1: math/rand のトップレベル関数(Go 1.20+ で Seed 未使用)
func BenchmarkRandV1TopLevel(b *testing.B) {
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            _ = rand.Float64()
        }
    })
}

// パターン2: 明示的な mutex 付き Source(Go 1.19 以前の挙動を再現)
func BenchmarkRandWithMutex(b *testing.B) {
    rng := rand.New(&lockedSource{src: rand.NewSource(1)})
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            _ = rng.Float64()
        }
    })
}

// パターン3: math/rand/v2 のトップレベル関数
func BenchmarkRandV2TopLevel(b *testing.B) {
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            _ = randv2.Float64()
        }
    })
}

// パターン4: goroutine ごとに独自の *rand.Rand を持つ
func BenchmarkRandPerGoroutine(b *testing.B) {
    b.RunParallel(func(pb *testing.PB) {
        rng := randv2.New(randv2.NewPCG(randv2.Uint64(), randv2.Uint64()))
        for pb.Next() {
            _ = rng.Float64()
        }
    })
}

// パターン5: sync.Pool を使う
var randPool = sync.Pool{
    New: func() interface{} {
        return randv2.New(randv2.NewPCG(randv2.Uint64(), randv2.Uint64()))
    },
}

func BenchmarkRandWithPool(b *testing.B) {
    b.RunParallel(func(pb *testing.PB) {
        for pb.Next() {
            rng := randPool.Get().(*randv2.Rand)
            _ = rng.Float64()
            randPool.Put(rng)
        }
    })
}

実行方法

go test -bench=. -benchmem -cpu=1,2,4,8,16 benchmark_rand_test.go

結果

ベンチマーク結果(Apple M2 Max, Go 1.25.4)

goos: darwin
goarch: arm64
cpu: Apple M2 Max

BenchmarkRandV1TopLevel         	162295452	   7.369 ns/op
BenchmarkRandV1TopLevel-2       	329617393	   3.637 ns/op
BenchmarkRandV1TopLevel-4       	664751200	   1.830 ns/op
BenchmarkRandV1TopLevel-8       	1000000000	   0.922 ns/op
BenchmarkRandV1TopLevel-16      	1000000000	   0.800 ns/op

BenchmarkRandWithMutex          	100000000	  10.29 ns/op
BenchmarkRandWithMutex-2        	 51640573	  24.37 ns/op
BenchmarkRandWithMutex-4        	  9841321	 118.3 ns/op
BenchmarkRandWithMutex-8        	 10081410	 120.2 ns/op
BenchmarkRandWithMutex-16       	 10328922	 116.1 ns/op

BenchmarkRandV2TopLevel         	210025754	   6.119 ns/op
BenchmarkRandV2TopLevel-2       	436139948	   2.756 ns/op
BenchmarkRandV2TopLevel-4       	876195144	   1.372 ns/op
BenchmarkRandV2TopLevel-8       	1000000000	   0.740 ns/op
BenchmarkRandV2TopLevel-16      	1000000000	   0.627 ns/op

BenchmarkRandPerGoroutine       	216559573	   5.581 ns/op
BenchmarkRandPerGoroutine-2     	434201247	   2.844 ns/op
BenchmarkRandPerGoroutine-4     	867199008	   1.383 ns/op
BenchmarkRandPerGoroutine-8     	1000000000	   0.701 ns/op
BenchmarkRandPerGoroutine-16    	1000000000	   0.527 ns/op

BenchmarkRandWithPool           	100000000	  10.21 ns/op
BenchmarkRandWithPool-2         	229883698	   5.061 ns/op
BenchmarkRandWithPool-4         	476546625	   2.531 ns/op
BenchmarkRandWithPool-8         	752687527	   1.609 ns/op
BenchmarkRandWithPool-16        	887312816	   1.373 ns/op

結果の解釈

パターン 1 CPU 4 CPU 16 CPU スケーリング
v1 TopLevel (現行) 7.4 ns 1.8 ns 0.8 ns 線形にスケール
WithMutex (Go 1.19 以前) 10.3 ns 118 ns 116 ns 頭打ち
v2 TopLevel 6.1 ns 1.4 ns 0.6 ns 線形にスケール
Per-Goroutine 5.6 ns 1.4 ns 0.5 ns 線形にスケール
sync.Pool 10.2 ns 2.5 ns 1.4 ns スケールするがオーバーヘッドあり

mutex がある場合(Go 1.19 以前の挙動):

  • 1 CPU → 4 CPU で約 11 倍悪化(10.3 ns → 118 ns)
  • 4 CPU 以降は頭打ち(Lock 待ちで goroutine がブロック)

per-P 実装(v2 / 現行 v1):

  • 並行数に比例してスループットがスケール
  • 16 CPU で 1 CPU の約 12 倍の性能

スループットのスケーリング(図)

throughput scaling

バージョン別まとめ

Go バージョン rand.Seed() トップレベル関数の実装 mutex で詰まる?
Go 1.19 以前 任意 lockedSource + mutex Yes
Go 1.20〜1.23 呼ばない runtimeSource (per-P) No
Go 1.20〜1.23 呼ぶ lockedSource に fallback Yes
Go 1.24+ no-op runtimeSource (per-P) No
math/rand/v2 存在しない runtimeSource (per-P) No

まとめ

2025 年現在、「rand.Float64() は mutex で遅い」という話は古い情報だった。

Go 1.19 以前なら正しかったし、Go 1.20〜1.23 で rand.Seed() を呼んでいるコードなら今でも正しい。でも Go 1.24 以降、あるいは math/rand/v2 を使っているなら、もう mutex のことは気にしなくていい。

移行のポイント

math/rand から math/rand/v2 への移行はシンプル。

// Before
import "math/rand"
x := rand.Float64()
n := rand.Intn(100)

// After
import "math/rand/v2"
x := rand.Float64()
n := rand.IntN(100)  // Intn → IntN に変更

あと、こういう初期化コードがあったら消していい。Go 1.20 以降は自動で適切に初期化されるし、Go 1.24 以降はそもそも何もしない。

// 消していい
func init() {
    rand.Seed(time.Now().UnixNano())
}

テストで乱数の再現性が必要なときだけ、自前の *rand.Rand を作ればいい。

rng := rand.New(rand.NewPCG(12345, 67890))
x := rng.Float64()

参考文献

  1. Evolving the Go Standard Library with math/rand/v2 - Go 公式ブログ
  2. math/rand/v2 package documentation - 公式ドキュメント
  3. GitHub Issue #61716: math/rand/v2 revised API - 提案と議論
  4. Go 1.20 Release Notes - リリースノート
  5. math/rand/v2 source code - 実装
  6. runtime/proc.go - G, M, P の定義
  7. Scheduling In Go: Part II - Go Scheduler - スケジューラの解説

Discussion