作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
在处理非常大的数组(例如 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/
在处理非常大的数组(例如 75000 个样本)时,removeSubrange 函数是否足够快?或者我应该使用任何其他更快的方法。 我可以通过如下所示的两种方式使用 removeSubrange。计算
static func trimBefore(string: inout String, char: Character) -> String { var newString = ""
我是一名优秀的程序员,十分优秀!