https://github.com/joway/fastrand
https://github.com/joway/fastrand
Last synced: about 1 year ago
JSON representation
- Host: GitHub
- URL: https://github.com/joway/fastrand
- Owner: joway
- Created: 2020-12-17T10:38:06.000Z (over 5 years ago)
- Default Branch: master
- Last Pushed: 2020-12-17T14:02:19.000Z (over 5 years ago)
- Last Synced: 2025-03-25T07:51:09.424Z (about 1 year ago)
- Language: Go
- Size: 3.91 KB
- Stars: 6
- Watchers: 2
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
Awesome Lists containing this project
README
# fastrand
## Background
Golang using a single [globalRand](https://github.com/golang/go/blob/master/src/math/rand/rand.go#L293) object between
multiple goroutines, which creates [race conditions](https://github.com/golang/go/issues/20387). And the exported method `rand.NewSource()` just creates a
non-thread-safe [rngSource]() object.
Fastrand wrap the internal `rngSource` struct into `sync.Pool`, and make it could run about **8 times** faster
than `globalRand` at the concurrent situation.
However, if you no need to share a single rand object within multiple goroutines, you could create a private rand.Rand
object for each goroutine.
## Install
```shell
go get github.com/joway/fastrand
```
## Usage
```go
rd := fastrand.New()
rd.Intn(100)
```
## Benchmark
```text
BenchmarkStandardRand
BenchmarkStandardRand-8 60870416 19.1 ns/op 0 B/op 0 allocs/op
BenchmarkFastRand
BenchmarkFastRand-8 100000000 10.7 ns/op 0 B/op 0 allocs/op
BenchmarkUnsafetyFastRand
BenchmarkUnsafetyFastRand-8 100000000 10.7 ns/op 0 B/op 0 allocs/op
BenchmarkStandardRandWithConcurrent
BenchmarkStandardRandWithConcurrent-8 18058663 67.8 ns/op 0 B/op 0 allocs/op
BenchmarkFastRandWithConcurrent
BenchmarkFastRandWithConcurrent-8 132542940 8.79 ns/op 0 B/op 0 allocs/op
```