Skip to content

Instantly share code, notes, and snippets.

@timvermeulen
Last active February 24, 2019 09:51
Show Gist options
  • Save timvermeulen/01617cd26f5ed25be81e59fd161bb98b to your computer and use it in GitHub Desktop.
Save timvermeulen/01617cd26f5ed25be81e59fd161bb98b to your computer and use it in GitHub Desktop.
import Foundation
func measure<T>(_ block: () -> T) -> T {
let start = Date()
let result = block()
print("elapsed time: \(-start.timeIntervalSinceNow)")
return result
}
extension Sequence {
func count(where predicate: (Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self {
if try predicate(element) {
count += 1
}
}
return count
}
func _count(where predicate: (Element) throws -> Bool) rethrows -> Int {
var count = 0
for element in self {
count += try predicate(element) ? 1 : 0
}
return count
}
}
let numbers = 0..<10_000_000_000
let evenCount = measure { numbers.count(where: { $0 % 2 == 0 }) } // elapsed time: 7.831457018852234
let _evenCount = measure { numbers._count(where: { $0 % 2 == 0 }) } // elapsed time: 5.888622999191284
precondition(evenCount == _evenCount)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment