Created
April 11, 2017 10:10
-
-
Save MayaLekova/b0100ebe6c3939021b6e778d1ca46edd to your computer and use it in GitHub Desktop.
Swift data structures time measurement
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
import Foundation | |
let collectionSize = 1000 | |
var arr = Array<UInt32>() | |
var arrInPlace = Array<UInt32>(repeating: 0, count: collectionSize) | |
var set = Set<UInt32>() | |
var dict = ["foo": 1, "bar": 2, "baz": 3] | |
func measure(_ function: () -> Void) -> Double { | |
let start = DispatchTime.now() | |
function() | |
let end = DispatchTime.now() | |
let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds | |
return Double(nanoTime) / 1_000_000_000 | |
} | |
func fillArr() { | |
for _ in 0..<collectionSize { | |
arr.append(arc4random()) | |
} | |
} | |
func fillArrInPlace() { | |
for i in 0..<collectionSize { | |
arrInPlace[i] = arc4random() | |
} | |
} | |
func fillSet() { | |
for _ in 0..<collectionSize { | |
set.insert(arc4random()) | |
} | |
} | |
print("Time to fill array: \(measure(fillArr)) seconds") | |
print("Time to fill array with preset size: \(measure(fillArrInPlace)) seconds") | |
print("Time to fill set: \(measure(fillSet)) seconds") | |
func sortArr() { | |
let arr2 = arr.sorted() | |
} | |
func sortSet() { | |
let arr2 = set.sorted() | |
} | |
print("Time to sort array: \(measure(sortArr)) seconds") | |
print("Time to sort set: \(measure(sortSet)) seconds") | |
func searchArr() { | |
let found = arr.contains(12345) | |
} | |
func searchSet() { | |
let found = set.contains(12345) | |
} | |
print("Time to search array: \(measure(searchArr)) seconds") | |
print("Time to search set: \(measure(searchSet)) seconds") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment