Created
July 30, 2016 01:54
-
-
Save CAD97/3e614c14dabc79e9e32e1a2229371fe6 to your computer and use it in GitHub Desktop.
Swift AnyIterator micro benchmark
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
// | |
// 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