gpt4 book ai didi

arrays - Swift removeSubrange 够快吗?

转载 作者:行者123 更新时间:2023-11-28 06:10:02 25 4
gpt4 key购买 nike

在处理非常大的数组(例如 75000 个样本)时,removeSubrange 函数是否足够快?或者我应该使用任何其他更快的方法。

我可以通过如下所示的两种方式使用 removeSubrange。计算时间是否有差异,特别是对于大样本量。

 import UIKit

var xt1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

var xt2 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

xt1.removeSubrange(ClosedRange(uncheckedBounds: (lower: 7, upper: 9)))

xt2.removeSubrange(7...9)

print("Method 1:", xt1)

print("Method 2:", xt2)

最佳答案

来自文档removeSubrange

Complexity: O(n), where n is the length of the collection.

对你来说尺寸太小了。

var x = Array(repeating: "yes", count: 750000)

比起我使用 Brad Larson 的代码进行测量:

func timeElapsedInSecondsWhenRunningCode(operation: ()->()) -> Double {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
return Double(timeElapsed)
}

所以让我们尝试进行测量。

timeElapsedInSecondsWhenRunningCode {
x.removeSubrange(4543...72000)
}

需要0.03秒

现在您可以进行一些测量并找出答案。

这是完整代码,将执行 32 次迭代以测量随机范围的性能。

var x = Array(repeating: "yes", count: 750000)

func timeElapsedInSecondsWhenRunningCode(from: Int, to: Int, operation: ()->()) -> Double {
let startTime = CFAbsoluteTimeGetCurrent()
operation()
let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
return Double(timeElapsed)
}

struct Test {
var range:(Int, Int)
var time:Double
}

var mesurments = [Int:Test]()

for i in 0...32 {

let from = randomInt(min: 0, max: x.count/2)

let to = randomInt(min: from, max: x.count)

let z = x

let time = timeElapsedInSecondsWhenRunningCode(from: from, to: to, operation: {
x.removeSubrange(from...to)
})

x = z

mesurments[i] = Test(range: (from, to), time: time)
}


func randomInt(min: Int, max:Int) -> Int {
return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}

关于arrays - Swift removeSubrange 够快吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47012739/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com