Skip to content

Instantly share code, notes, and snippets.

@erica
Last active February 14, 2019 20:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save erica/7b893ea362d072d3a80bb80fc792a8af to your computer and use it in GitHub Desktop.
Save erica/7b893ea362d072d3a80bb80fc792a8af to your computer and use it in GitHub Desktop.
//-----------------------------------------------------------------------------
// MARK: Time Test
//-----------------------------------------------------------------------------
import Foundation
/// Prints the elapsed time to execute a block under whatever optimization
/// conditions are currently in use by the compiler
public func timetest(_ note: String, block: () -> Void) {
print("Starting Test:", note)
let now = ProcessInfo().systemUptime
block()
let timeInterval = ProcessInfo().systemUptime - now
print("Ending Test:", note); print("Elapsed time: \(timeInterval)")
}
extension Int {
var isOdd: Bool { return !self.isMultiple(of: 2) }
}
public func test() {
let TESTCOUNT = 100_000
let VALUECOUNT = 1_000
var nums: [Int] = []
// Fill up with random numbers, so the tests should never succeed
for _ in 1 ... VALUECOUNT {
nums.append(Int.random(in: 1 ... 1_000_000))
}
print("Running \(TESTCOUNT) tests on an array of \(VALUECOUNT) values")
timetest("contains") {
var wins = 0
for _ in 1 ... TESTCOUNT {
// every element is 9
let success1 = !nums.contains(where: { $0 != 9 })
// every element is odd
let success2 = !nums.contains(where: { !$0.isOdd })
wins += success1 || success2 ? 1 : 0
}
print("Note: wincount sink: \(wins)")
}
timetest("reduce") {
var wins = 0
for _ in 1 ... TESTCOUNT {
// every element is 9
let success1 = nums.reduce(true, { $0 && $1 == 9 })
// every element is odd
let success2 = nums.reduce(true, { $0 && $1.isOdd })
wins += success1 || success2 ? 1 : 0
}
print("Note: wincount sink: \(wins)")
}
timetest("allSatisfy") {
var wins = 0
for _ in 1 ... TESTCOUNT {
// every element is 9
let success1 = nums.allSatisfy({ $0 == 9 })
// every element is odd
let success2 = nums.allSatisfy({ $0.isOdd })
wins += success1 || success2 ? 1 : 0
}
print("Note: wincount sink: \(wins)")
}
timetest("filter") {
var wins = 0
for _ in 1 ... TESTCOUNT {
// every element is 9
let success1 = nums.filter({ $0 != 9 }).isEmpty
// every element is odd
let success2 = nums.filter({ !$0.isOdd }).isEmpty
wins += success1 || success2 ? 1 : 0
}
print("Note: wincount sink: \(wins)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment