Created
July 30, 2016 01:11
-
-
Save CAD97/60d595d3543c40111190b7d60a1c314b to your computer and use it in GitHub Desktop.
Swift removeFirst/Last 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 = 600 | |
let ITERATIONS = 10_000 | |
// MARK: removeFirst | |
var firstTest: [TimeInterval] = [] | |
let startFirstTest = Date() | |
for _ in 1...TRIALS { | |
var test = Array(repeating: 5, count: ITERATIONS) | |
let start = Date() | |
while test.count > 0 { | |
test.removeFirst() | |
} | |
let end = Date() | |
firstTest.append(end.timeIntervalSince(start)) | |
} | |
let endFirstTest = Date() | |
let firstTestTime = endFirstTest.timeIntervalSince(startFirstTest) | |
let firstSum = firstTest.reduce(0, combine: +) | |
let firstAvg = firstSum / Double(firstTest.count) | |
let firstMax = firstTest.reduce(DBL_MIN, combine: {$0 > $1 ? $0 : $1}) | |
let firstMin = firstTest.reduce(DBL_MAX, combine: {$0 < $1 ? $0 : $1}) | |
print(String(format:"removeFirst took %f s for \(ITERATIONS) iterations over \(TRIALS) trials", firstAvg)) | |
print(String(format: "with a max of %f and a min of %f . The test took %f s.", firstMax, firstMin, firstTestTime)) | |
print() | |
// MARK: removeLast | |
var lastTest: [TimeInterval] = [] | |
let startLastTest = Date() | |
for _ in 1...TRIALS { | |
var test = Array(repeating: 5, count: ITERATIONS) | |
let start = Date() | |
while test.count > 0 { | |
test.removeLast() | |
} | |
let end = Date() | |
lastTest.append(end.timeIntervalSince(start)) | |
} | |
let endLastTest = Date() | |
let lastTestTime = endLastTest.timeIntervalSince(startLastTest) | |
let lastSum = lastTest.reduce(0, combine: +) | |
let lastAvg = lastSum / Double(lastTest.count) | |
let lastMax = lastTest.reduce(DBL_MIN, combine: {$0 > $1 ? $0 : $1}) | |
let lastMin = lastTest.reduce(DBL_MAX, combine: {$0 < $1 ? $0 : $1}) | |
print(String(format:"removeLast took %f s for \(ITERATIONS) iterations over \(TRIALS) trials", lastAvg)) | |
print(String(format: "with a max of %f and a min of %f . The test took %f s.", lastMax, lastMin, lastTestTime)) | |
print() | |
/* | |
removeFirst took 0.096540 s for 10000 iterations over 600 trials | |
with a max of 0.165383 and a min of 0.095035 . The test took 57.938797 s. | |
removeLast took 0.083069 s for 10000 iterations over 600 trials | |
with a max of 0.145710 and a min of 0.082141 . The test took 49.852311 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