- tstm
- Jun 4, 2014
-
|
The optimizer seems to do some really weird things for me.
I ported this benchmarking simulation to Swift.
After long periods of toying around with different things I actually got out something that performs nicely: http://tstm.info/files/nbody.swift
But for some reason I still have to do very odd things to be able to make it performant. In the function advance() I'm doing an extra code: let _planets = planets
without any good reason.
If I take it away, and replace the advance() function with something like this:
code:func advance(dt: Double) {
var n = planets.count
for var i = 0; i < n ; i++ {
let iPlanet = planets[i]
for var j = i+1; j < n; j++ {
let jPlanet = planets[j]
let dx = iPlanet.x - jPlanet.x
let dy = iPlanet.y - jPlanet.y
let dz = iPlanet.z - jPlanet.z
let dSquared = dx * dx + dy * dy + dz * dz
let distance = sqrt(dSquared)
let mag = dt / (dSquared * distance)
planets[i].vx -= dx * jPlanet.mass * mag
planets[i].vy -= dy * jPlanet.mass * mag
planets[i].vz -= dz * jPlanet.mass * mag
planets[j].vx += dx * iPlanet.mass * mag
planets[j].vy += dy * iPlanet.mass * mag
planets[j].vz += dz * iPlanet.mass * mag
}
}
for var i = 0; i < n ; i++ {
planets[i].x += dt * planets[i].vx
planets[i].y += dt * planets[i].vy
planets[i].z += dt * planets[i].vz
}
}
The code slows down tenfold. I do not understand why this might be happening - and I'm really trying to code within reasonable standards here, I'm not a good programmer by any stretch, but something doesn't seem quite right in the optimizer. Or is it me doing something horribly wrong?
Also, I've found that using a static or a dynamic Array to store the bodies in will result in lots and lots and lots of retain/release, and that's why I had to go and use a static-size ContiguousArrayBuffer instead of an Array.
As for the actual results, with the weird "optimizations" I had to do, I can run 5 000 000 iterations of nbody in ~3.8 seconds on my rMBP. The original Java code I ported does the same in 0.9s - swift is slower but not by that much, and I'm sure there could be other things still going wrong.
|
#
¿
Jun 4, 2014 13:36
|
|
- Adbot
-
ADBOT LOVES YOU
|
|
#
¿
May 4, 2024 09:46
|
|