Skip to content

Instantly share code, notes, and snippets.

@CAD97
Created July 30, 2016 01:54
Show Gist options
  • Save CAD97/3e614c14dabc79e9e32e1a2229371fe6 to your computer and use it in GitHub Desktop.
Save CAD97/3e614c14dabc79e9e32e1a2229371fe6 to your computer and use it in GitHub Desktop.
Swift AnyIterator micro benchmark
//
// main.swift
// microbenchmark
//
// Created by Christopher Durham on 7/29/16.
// Copyright © 2016 Christopher Durham. All rights reserved.
//
import Foundation
let TRIALS = 10_000
let ITEMS = 10_000
var test: [TimeInterval] = []
let startTest = Date()
for _ in 1...TRIALS {
let array = Array(repeating: 5, count: ITEMS)
var iterator = array.makeIterator()
let startRegular = Date()
while let i = iterator.next() { }
let endRegular = Date()
var iterator2 = AnyIterator(array.makeIterator())
let startAny = Date()
while let i = iterator2.next() { }
let endAny = Date()
let regular = endRegular.timeIntervalSince(startRegular)
let any = endAny.timeIntervalSince(startRegular)
test.append(any - regular)
}
let endTest = Date()
let testTime = endTest.timeIntervalSince(startTest)
let sum = test.reduce(0, combine: +)
let avg = sum / Double(test.count)
let max = test.reduce(DBL_MIN, combine: {$0 > $1 ? $0 : $1})
let min = test.reduce(DBL_MAX, combine: {$0 < $1 ? $0 : $1})
print(String(format:"A difference of %f s for \(ITEMS) items over \(TRIALS) trials", avg))
print(String(format: "with a max of %f and a min of %f . The test took %f s.", max, min, testTime))
print()
/*
A difference of 0.005833 s for 10000 items over 10000 trials
with a max of 0.021026 and a min of 0.005713 . The test took 59.240558 s.
Program ended with exit code: 0
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment