我在scala中尝试了一些东西,发现下面的代码证明了奇怪的性能问题。在这里内联函数调用使得计算需要4倍(4秒对16秒)。
package mypackage
object MyObject extends Application {
class Complex(val real: Double, val imaginary: Double) {
def +(operand: Complex): Complex = {
new Complex(real + operand.real, imaginary + operand.imaginary)
}
def *(operand: Complex): Complex = {
new Complex(real * operand.real - imaginary * operand.imaginary,
real * operand.imaginary + imaginary * operand.real)
}
def mag2 = real * real + imaginary * imaginary
}
val iSize = 1250
val jSize = 1250
val xMin = -2.5
val xMax = +1.5
val yMin = -2.0
val yMax = +2.0
val dx = (xMax - xMin) / iSize
val dy = (yMax - yMin) / jSize
val steps = 50
def iterate(c: Complex) = {
var z = c
var n = 0
do {
z = z * z + c
n += 1
} while (n < steps && z.mag2 < 4.0)
}
// Mandelbrot set using iteration in a function.
var startTime = System.currentTimeMillis()
for (i <- 0 until iSize; j <- 0 until jSize) {
val c = new Complex(xMin + i * dx, yMin + j * dy)
iterate(c)
}
System.out.println("Elapsed time: " + (System.currentTimeMillis() - startTime) / 1000.0 + " (s)")
// Mandelbrot set using iteration.
startTime = System.currentTimeMillis()
for (i <- 0 until iSize; j <- 0 until jSize) {
val c = new Complex(xMin + i * dx, yMin + j * dy)
var z = c
var n = 0
do {
z = z * z + c
n += 1
} while (n < steps && z.mag2 < 4.0)
}
System.out.println("Elapsed time: " + (System.currentTimeMillis() - startTime) / 1000.0 + " (s)")
}
知道为什么会这样吗?在“迭代”功能之前添加“@inline”使得它需要12秒对4秒。
答案 0 :(得分:1)
请将应用程序替换为应用程序,并获得100倍的加速。