Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Measuring performance of three different algorithms for calculating the average for an array of doubles
import Foundation
extension Array where Element: FloatingPoint {
func average() -> Element {
// one addition and one division per array item
return reduce(0) { result, value in result + value / Element(count) }
}
func average2() -> Element {
// number of items minus one additions and one division.
return reduce(0, +)/Element(count)
}
func average3() -> Element {
var average: Element = 0
forEach() { e in
average += e
}
return average / Element(count)
}
}
func measureTime(_ block: (() -> Void)) {
let start = DispatchTime.now()
block()
let end = DispatchTime.now()
let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds
let timeInterval = Double(nanoTime) / 1_000_000_000
print("Time: \(timeInterval) seconds")
}
// uses 80 MB of memory
let longList: [Double] = (1...1_000_0000).map { _ in Double.random(in: (0...1.0e23)) }
measureTime() {
print("average")
let average = longList.average()
print("average: \(average)")
}
measureTime() {
print("average2")
let average = longList.average2()
print("average2: \(average)")
}
measureTime() {
print("average3")
let average = longList.average3()
print("average3: \(average)")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment