为什么Int.random()比arc4random_uniform()慢?

Ada*_*nke 5 random swift

我已经使用Int.random()方法和arc4random_uniform()进行了数字生成速度测试。
两项测试均在macOS控制台中运行,并将构建配置设置为release。以下是我用于测试的代码。

public func randomGen1() {
    let n = 1_000_000
    let startTime = CFAbsoluteTimeGetCurrent()
    for i in 0..<n {
        _ = arc4random_uniform(10)
    }
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print(timeElapsed)
}
public func randomGen2() {
    let n = 1_000_000
    let startTime = CFAbsoluteTimeGetCurrent()
    for i in 0..<n {
        _ = Int.random(in: 0..<10)
    }
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print(timeElapsed)
}
Run Code Online (Sandbox Code Playgroud)

我得到的时间是
0.029475092887878418(用于arc4random_uniform(10))
0.20298802852630615(用于Int.random(in:0 .. <10))

为什么Int.random()这么慢?
有没有优化的方法?
有没有更快的方法快速生成随机数?

iel*_*ani 2

更新

区间内随机数生成器的这种实现已合并到标准库中,并且应该比以前表现得更好:

// s = upperBound; r1, r2 = random numbers from generator
func bounded(s: UInt64, r1:UInt64, r2: UInt64) -> UInt64 {
    // r1 would come from invoking generator's next()
    var m = r1.multipliedFullWidth(by: s)
    if m.low < s {
        // let t = (0 &- s) % s // Lemire's original form
        var t = 0 &- s // O'Neill's modulo optimization
        if t >= s {
            t &-= s
            if t >= s {
                t %= s
            }
        }
        while m.low < t {
            // r2 would come from invoking generator's next()
            m = r2.multipliedFullWidth(by: s)
        }
    }
    return m.high
}
Run Code Online (Sandbox Code Playgroud)

请参阅下面的答案了解更多详细信息。

回答

你的第二个问题的答案:

“有没有更快的方法来快速生成随机数?”

之前使用过Xoshiro伪随机数生成器,速度相当快。

这里是用于基准测试的代码:

  • 随机Gen1
import Foundation

public func randomGen1() {
    let n = 1_000_000
    var sum: UInt32 = 0
    let startTime = CFAbsoluteTimeGetCurrent()
    for _ in 0..<n {
        sum = sum &+ arc4random_uniform(10)
    }
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print(sum, timeElapsed)
}

do {
    randomGen1()
}
Run Code Online (Sandbox Code Playgroud)
  • 随机Gen2
public func randomGen2() {
    let n = 1_000_000
    var sum: UInt32 = 0
    let startTime = CFAbsoluteTimeGetCurrent()
    for _ in 0..<n {
        sum = sum &+ UInt32.random(in: 0..<10)
    }
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print(sum, timeElapsed)
}


do {
    randomGen2()
}
Run Code Online (Sandbox Code Playgroud)
struct Xoshiro: RandomNumberGenerator {
    public typealias StateType = (UInt32, UInt32, UInt32, UInt32)

    private var state: StateType

    public init(seed: StateType) {
        self.state = seed
    }

    public mutating func next() -> Int {
        let x = state.1 &* 5
        let result = ((x &<< 7) | (x &>> 25)) &* 9
        let t = state.1 &<< 9
        state.2 ^= state.0
        state.3 ^= state.1
        state.1 ^= state.2
        state.0 ^= state.3
        state.2 ^= t
        state.3 = (state.3 &<< 21) | (state.3 &>> 11)
        return Int(result)
    }
}

var x = Xoshiro(seed: (UInt32.random(in: 0..<10),  //Other upper limits could be used to increase randomness
    UInt32.random(in: 0..<10),
    UInt32.random(in: 0..<10),
    UInt32.random(in: 0..<10)))

public func randomGen3() {
    let n = 1_000_000
    var sum: UInt32 = 0
    let startTime = CFAbsoluteTimeGetCurrent()
    for _ in 0..<n {
        sum = sum &+ UInt32(abs(x.next()) % 10)
    }
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print(sum, timeElapsed)
}

do {
    randomGen3()
}
Run Code Online (Sandbox Code Playgroud)

Xoshiro 速度很快,但没有通过所有随机性测试。如果担心安全性,那么您可以使用Wyhash

Daniel Lemire (本文作者)刚刚向我发送了Wyhash 的Swift 实现

class WyhashGenerator {
    var seed : UInt64

    let multiplier1 : UInt64 = 0xa3b195354a39b70d
    let multiplier2 : UInt64 = 0x1b03738712fad5c9
    let increment : UInt64 = 0x60bee2bee120fc15

    init(userSeed : UInt64) {
        seed = userSeed;
    }

    func random() -> UInt64 {
        seed &+= increment
        let fullmult1 = seed.multipliedFullWidth(by: multiplier1)
        let m1 = fullmult1.high ^ fullmult1.low;
        let fullmult2 = m1.multipliedFullWidth(by: multiplier2)
        let m2 = fullmult2.high ^ fullmult2.low;
        return m2
    }
}
Run Code Online (Sandbox Code Playgroud)

它可以像这样使用:

public func randomGen4() {
    let n = 1_000_000
    var sum: UInt64 = 0
    let startTime = CFAbsoluteTimeGetCurrent()
    let gen = WyhashGenerator(userSeed: 0)
    for _ in 0..<n {
        sum = sum &+ gen.random() % 10
    }
    let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
    print(sum, timeElapsed)
}

do {
    randomGen4()
}
Run Code Online (Sandbox Code Playgroud)

以下是基准测试结果,在终端中编译的代码经过优化 ( -O) :

arc4random_uniform()  : 0.034s
UInt32.random(in:)    : 0.243s
WyHash64              : 0.002s
Xoshiro               : 0.001s
Run Code Online (Sandbox Code Playgroud)

您可以在这里找到更多随机数生成器。

  • 从 SystemRandomNumberGenerator 切换到 Xoshiro 时请务必慎重。前者是尽可能加密安全的 PRNG。Xoshiro 不是加密安全的 PRNG。这类事情原本并不重要,直到它突然变得非常重要。CSPRNG 的安全性会带来性能成本,因此任何像样的非 CSPRNG 都应该更快。 (8认同)
  • 请注意,RandomNumberGenerator 必须实现 `public mutating func next() -&gt; UInt64` - 然后您可以调用 `Int.random(in: 0..&lt;10, using: &amp;x)` 而不是模算术(这会受到“模偏差”问题)。 (4认同)