vendredi 26 avril 2019

Why is Int.random() ruining slower than arc4random_uniform()?

I have used Int.random() method and arc4random_uniform() for number generation speed tests.
Both tests were run in macOS console with build configuration set to release. Below are codes which I have used for testing.

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)
}

The times I got are
0.029475092887878418 (for arc4random_uniform(10))
0.20298802852630615 (for Int.random(in: 0..<10))

Why is Int.random() so much slower?
Is there a way to optimise it?
Are there any faster methods for random number generation in swift?




Aucun commentaire:

Enregistrer un commentaire