# Golang rand 库锁竞争优化

DevFeed: [Golang rand 库锁竞争优化](<https://devfeed.tech/articles/golang-rand-40984.md>)

Original publisher: [Read original article](<https://blog.joway.io/posts/golang-fastrand/>)

Author: Joway

Published: 2020-12-17T00:00:00Z

Content type: tutorial

Language: zh

Sources: [Random Thoughts](<https://devfeed.tech/sources/random-thoughts.md>)

Topics: [Benchmark](<https://devfeed.tech/topics/benchmark.md>)

Tags: [benchmark](<https://devfeed.tech/tags/benchmark.md>), [golang](<https://devfeed.tech/tags/golang.md>), [tech](<https://devfeed.tech/tags/tech.md>)

## AI overview

This article explains how contention around Go's globally shared random number generator can reduce performance under high concurrency. It presents a fastrand library that uses pooled per-processor state to reduce lock contention and reports approximately eightfold faster performance than the native global rand in concurrent benchmarks.

## Source excerpt

背景 最近在实现一个随机负载均衡器的时候发现一个问题，在高并发的情况下，官方标准库 rand.Intn() 性能会急剧下降。翻了下实现以后才发现它内部居然是全局共享了同一个 globalRand 对象。 一段测试代码： func BenchmarkGlobalRand(b *testing.B) { b.RunParallel(func(pb *testing.PB) { for pb.Next() { rand.Intn(100) } }) } func BenchmarkCustomRand(b *testing.B) { b.RunParallel(func(pb *testing.PB) { rd := rand.New(rand.NewSource(time.Now().Unix())) for pb.Next() { rd.Intn(100) } }) } 输出：