Skip to content

Instantly share code, notes, and snippets.

@twostraws
Created January 28, 2020 23:44
Show Gist options
  • Save twostraws/2e60175d38d9bf65c60201ab3c3c786f to your computer and use it in GitHub Desktop.
Save twostraws/2e60175d38d9bf65c60201ab3c3c786f to your computer and use it in GitHub Desktop.
A microbenchmark for a potential Swift standard library addition
//
// FOR FOLKS STUMBLING ACROSS THIS LATER
// This is an example of code that allows us to create arrays by calling a function a fixed number of times.
// In my example below I'm just sending in 5 because I don't want to cloud the benchmark with generating
// a random number or similar, but with this change you can replace the 5 with `Int.random(in: 1...10)` to
// get an array of random numbers.
//
// HERE'S THE STDLIB ADDITION TO MAKE THIS WORK:
// @inlinable
// @_semantics("array.init")
// public init(builder body: @autoclosure () -> Element, count: Int) {
// var p: UnsafeMutablePointer<Element>
// (self, p) = Array._allocateUninitialized(count)
// for _ in 0..<count {
// p.initialize(to: body())
// p += 1
// }
// }
import Foundation
let repeatCount = 1000000
for i in 1...10 {
print("Run \(i):")
var start = CFAbsoluteTimeGetCurrent()
let randomNumbers = [Int](builder: 5, count: repeatCount)
print("New: Generated \(randomNumbers.count) item array in \(CFAbsoluteTimeGetCurrent() - start) seconds")
start = CFAbsoluteTimeGetCurrent()
let currentMethod = (1...repeatCount).map { _ in 5 }
print("Old: Generated \(currentMethod.count) item array in \(CFAbsoluteTimeGetCurrent() - start) seconds")
print("")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment