-
-
Save TellowKrinkle/37e7c9c00ccd68f65353fb550af68951 to your computer and use it in GitHub Desktop.
Swift Foundation.Data 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
import Foundation | |
let n: Int | |
if CommandLine.arguments.count > 3, let int = Int(CommandLine.arguments[3]) { | |
n = 1 << int | |
} else { | |
n = 1 << 26 | |
guard CommandLine.arguments.count >= 3 else { | |
print("Usage: \(CommandLine.arguments[0]) datastructure test [log(iterations)]") | |
exit(EXIT_FAILURE) | |
} | |
} | |
protocol InitRepeatingCollection: Collection { | |
init(repeating: Element, count: Int) | |
} | |
extension Data: InitRepeatingCollection {} | |
extension Array: InitRepeatingCollection {} | |
func stringTest<C: Collection>(_ col: C) where C.Element == UInt8 { | |
let string = String(decoding: col, as: UTF8.self) | |
print(string.last!) | |
} | |
func reduceTest<C: Collection>(_ col: C) where C.Element == UInt8 { | |
print(col.reduce(0, { $0 + Int($1) })) | |
} | |
func sliceTest<C: Collection>(_ col: C) where C.Element == UInt8 { | |
var slice = col[...] | |
var count = 0 | |
var total = 0 | |
while !slice.isEmpty { | |
total += Int(slice.first!) | |
count += 1 | |
slice = slice[slice.index(after: slice.startIndex)...] | |
} | |
print(count) | |
print(total) | |
} | |
func forTest<C: Collection>(_ col: C) where C.Element == UInt8 { | |
var count = 0 | |
var total = 0 | |
for item in col { | |
count += 1 | |
total += Int(item) | |
} | |
print(count) | |
print(total) | |
} | |
func allocTest<C: InitRepeatingCollection>(_ type: C.Type, n: Int) where C.Element == UInt8 { | |
let c = (0..<n).map({ _ in C(repeating: 97, count: 32) }) | |
print(c[0]) | |
} | |
func test<C: InitRepeatingCollection>(_ type: C.Type, testName: String, n: Int) where C.Element == UInt8 { | |
if testName == "alloc" { | |
allocTest(C.self, n: n) | |
} else { | |
let col = C(repeating: 97 /* ASCII a */, count: n) | |
switch testName { | |
case "reduce": reduceTest(col) | |
case "string": stringTest(col) | |
case "slice": sliceTest(col) | |
case "for": forTest(col) | |
default: print("Unsupported test") | |
} | |
} | |
} | |
let testName = CommandLine.arguments[1].lowercased() | |
switch CommandLine.arguments[2].lowercased() { | |
case "array": | |
test([UInt8].self, testName: testName, n: n) | |
case "data": | |
test(Data.self, testName: testName, n: n) | |
default: | |
print("Unsupported data structure") | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment