Last active
October 19, 2022 17:54
-
-
Save karwa/35d33be3924e1372197e5e9f5d61363e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
extension Collection { | |
public subscript(inplace_slice bounds: Range<Index>) -> Slice<Self> { | |
get { fatalError() } | |
_modify { | |
var slice = Slice(base: self, bounds: bounds) | |
yield &slice | |
} | |
} | |
} | |
extension RangeReplaceableCollection where Self: MutableCollection { | |
public subscript(inplace_native bounds: Range<Self.Index>) -> Self.SubSequence { | |
get { fatalError() } | |
_modify { | |
yield &self[bounds] | |
} | |
} | |
} | |
import Foundation | |
enum Operation: String { | |
case sort = "Append" | |
case append = "Sort" | |
case removeAll = "RemoveAll" | |
} | |
let op = Operation.removeAll | |
let iterations = 1000 | |
var randomArrays = [[Int]]() | |
func reset() { | |
randomArrays.removeAll() | |
for _ in 0..<iterations { | |
var testArray = [Int]() | |
for _ in 0..<10_000 { | |
testArray.append(Int.random(in: 0 ... .max)) | |
} | |
randomArrays.append(testArray) | |
} | |
} | |
reset() | |
let start_norm = CFAbsoluteTimeGetCurrent() | |
for i in 0..<iterations { | |
switch op { // This should get optimised away. | |
case .sort: | |
randomArrays[i][0..<5000].sort() | |
case .append: | |
randomArrays[i][0..<5000].append(42) | |
case .removeAll: | |
randomArrays[i][0..<5000].removeAll() | |
} | |
} | |
let end_norm = CFAbsoluteTimeGetCurrent() | |
let time_norm = (end_norm - start_norm) / Double(iterations) | |
reset() | |
let start_slice = CFAbsoluteTimeGetCurrent() | |
for i in 0..<iterations { | |
switch op { | |
case .sort: | |
randomArrays[i][inplace_slice: 0..<5000].sort() | |
case .append: | |
randomArrays[i][inplace_slice: 0..<5000].append(42) | |
case .removeAll: | |
randomArrays[i][inplace_slice: 0..<5000].removeAll() | |
} | |
} | |
let end_slice = CFAbsoluteTimeGetCurrent() | |
let time_slice = (end_slice - start_slice) / Double(iterations) | |
reset() | |
let start_array = CFAbsoluteTimeGetCurrent() | |
for i in 0..<iterations { | |
switch op { | |
case .sort: | |
randomArrays[i][inplace_native: 0..<5000].sort() | |
case .append: | |
randomArrays[i][inplace_native: 0..<5000].append(42) | |
case .removeAll: | |
randomArrays[i][inplace_native: 0..<5000].removeAll() | |
} | |
} | |
let end_array = CFAbsoluteTimeGetCurrent() | |
let time_array = (end_array - start_array) / Double(iterations) | |
print(""" | |
Test Results (\(op.rawValue)): | |
Iterations: \(iterations) | |
Regular subscript: \(time_norm * 1000) ms | |
modify generic Slice<T>: \(time_slice * 1000) ms | |
modify native SubSeq: \(time_array * 1000) ms | |
""") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment