Created
January 28, 2020 23:44
-
-
Save twostraws/2e60175d38d9bf65c60201ab3c3c786f to your computer and use it in GitHub Desktop.
A microbenchmark for a potential Swift standard library addition
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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