我一直在尝试优化代码以降低 CPU 使用率。我已经重写了这些函数几次都无济于事,寻求一些帮助。
63% 的时间花在了……最多只有 24 个 child 的线上。
func totalMass() -> CGFloat {
var ret : CGFloat = 0
for ball in self.children as! [Ball] {
ret += ball.mass
}
return ret
}
几乎 90% 的时间都花在了 if distance(food...) 上,一次可以有超过 800 block “食物”。
func randomMove() {
confidenceLevel = 0
if let b = self.children.first as! Ball? {
if b.physicsBody?.velocity == CGVector(dx: 0, dy: 0) {
//print("a")
self.move(randomPosition())
} else if b.position.x + b.radius > 1950 || b.position.x - b.radius < -1950 {
//print("here", b.position.x, b.radius)
self.move(randomPosition())
} else if b.position.y + b.radius > 1950 || b.position.y - b.radius < -1950 {
//print("there")
self.move(randomPosition())
} else {
// Keep moving
let scene : GameScene = self.scene as! GameScene
for food in scene.foodLayer.children as! [Food] {
if distance (food.position, p2: self.centerPosition()) < b.radius * 5 {
self.move(food.position)
return
}
}
}
}
}
100% 的时间花在结束花括号 }) 第三个 IF 语句之前
override func didSimulatePhysics() {
world.enumerateChildNodesWithName("//ball*", usingBlock: {
node, stop in
let ball = node as! Ball
ball.regulateSpeed()
if let body = ball.physicsBody {
if (body.velocity.speed() > 0.01) {
ball.zRotation = body.velocity.angle() - self.offset
}
}
})
if let p = currentPlayer {
centerWorldOnPosition(p.centerPosition())
} else if playerLayer.children.count > 0 {
let p = playerLayer.children.first! as! Player
centerWorldOnPosition(p.centerPosition())
} else {
centerWorldOnPosition(CGPoint(x: 0, y: 0))
}
}
最佳答案
你知道关于渔夫的老话吗? 给他一条鱼,你喂他一天。 授人以渔,终身受用。
与其告诉您要修复什么,不如让我解释一下如何通过手动采样找到加速。
让我们假设您的代码可以变得更快(很可能)。如果你这样做,它会节省一些时间,比如 20%。 这意味着您要优化的特定详细事件,无论是什么,实际上至少有 20% 的时间在执行过程中。
它可能会执行更多的时间,比如 40%。 只是您的优化可能无法摆脱所有这些。 你可能只摆脱了一半,所以你可能只有 20%。
这意味着如果您随机停止它,并检查它在那个时间点所做的一切细节以及原因,您将有 40% 的机会看到它正在做您正在做的事情去优化,浪费的东西。
您怎么知道您看到的内容虽然很浪费,但是否有足够的时间来解决问题? 你知道吗,如果你第二次看到它。 看到某些东西一次并不能告诉你太多 - 只是它需要非零时间, 但是当您第二次看到它时,您不知道它有多大,但您确实知道它不小。 在看到两次之前采样的次数越少,它就越大。 Here are the statistics.
因此,如果它要节省 20%,并且如果它执行 40% 的时间,那么在看到它两次之前您需要多少样本? 平均而言,2/.4,即 5 个样本。 如果你取 10 个样本,你期望看到它多少次?四。 如果您采集 10 个样本,您不会多次看到它的概率是多少? 4.5% 如果你取 20 个样本,你错过它的概率是多少?几乎为零。
这就是手动采样的威力。 您可以看到程序正在做什么以及为什么这样做的精确细节。 这是剖析器不会告诉你的。 他们采集了更多的样本,然后将它们拼凑成时序数字,因此您可以看到所谓的“热代码”,但您只能猜测如何修复它。 手动检查少量样本,详细地,用你所有的程序员智慧去理解每一个样本,告诉你确切。
这就是为什么 this post ,虽然与常识相反,但有如此多的选票。 您可以从中获得更快的速度。
关于ios - 优化代码物理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38386453/