Mandelbrot刷新速度非常慢,有什么方法可以让它更快?
我最近一直在研究分形生成器,并且一直专门研究Mandelbrot集。不幸的是,缩放和移动似乎非常不方便,需要一段时间才能刷新。我每次缩放都会生成它,而且我知道这可能不是实现此目的的最有效方式,而且我似乎无法找到使用我了解的另一种方法的代码。 这些是我使用的以下方法,第一个是初始生成,第二个是刷新方法。Mandelbrot刷新速度非常慢,有什么方法可以让它更快?
private void genMandelbrot(Dimension size) {
for(int x=0;x<size.width;x++) {
for(int y=0;y<size.height;y++) {
double moveX=globalx;
double moveY=globalx;
//zoom and x/y offset.
double real = 1.5 * (x - size.width/2)/(0.5 * zoom * size.width) + moveX;
double imaginary=(y - size.height/2)/(0.5 * zoom * size.height) + moveY;
double newRe=0,newIm=0,oldRe=0,oldIm=0;
int i;
for(i=0;i<8000;i++) {
oldRe = newRe;
oldIm = newIm;
newRe = oldRe * oldRe - oldIm * oldIm + real;
newIm = 2 * oldRe * oldIm + imaginary;
if((newRe * newRe + newIm * newIm) > 4) break;
}
Cell c = new Cell(Color.getHSBColor(i % 256, i % 255, 255 * ((i<20)? 1:0)), new Dimension(1,1), new Point(x,y));
cells.add(c);
}
}
}
public void refreshMandelbrot(Dimension size) {
for(Cell c : cells) {
double moveX=globalx;
double moveY=globalx;
int x=c.x;
int y=c.y;
//zoom and x/y offset.
double real = 1.5 * (x - size.width/2)/(0.5 * zoom * size.width) + moveX;
double imaginary=(y - size.height/2)/(0.5 * zoom * size.height) + moveY;
double newRe=0,newIm=0,oldRe=0,oldIm=0;
int i;
for(i=0;i<8000;i++) {
oldRe = newRe;
oldIm = newIm;
newRe = oldRe * oldRe - oldIm * oldIm + real;
newIm = 2 * oldRe * oldIm + imaginary;
if((newRe * newRe + newIm * newIm) > 4) break;
}
cells.set(cells.indexOf(c), new Cell(Color.getHSBColor(i % 256, i % 255, 255 * ((i<20)? 1:0)), new Dimension(1,1), new Point(x,y)));
}
System.out.println("Set refreshed.");
}
我想cells
是某种List
的实现?
在这种情况下,你的刷新方法的大部分时间都是花费在这一行:
cells.set(cells.indexOf(c), new Cell(Color.getHSBColor(i % 256, i % 255, 255 * ((i<20)? 1:0)), new Dimension(1,1), new Point(x,y)));
更确切地说在cells.indexOf(c)
,在整个列表迭代找到c
正确的索引。
由于您只是更改每个单元格的颜色,所以最简单的解决方法是更改当前正在使用的单元格的颜色。我不知道实际的实现你的Cell
类的,但如果它有一个方法setColor(...)
,你可以用
c.setColor(Color.getHSBColor(i % 256, i % 255, 255 * ((i<20)? 1:0)));
这降低了refreshMandelbrot
方法的运行时一样的替换上面的行方法genMandelbrot
。
我不知道Cell
类的用途,但如果仅将它用作颜色的包装,则如果将计算的每个像素的颜色存储在二维中,则可能会获得更多的性能数组或直接写入Graphics
或Raster
对象,而不是处理单元包装的平面列表。
您很可能需要细分分形并计算不那么有趣的瓷砖。 8000 repetiton是很多。您还可以简化计算一下。
配置文件尝试优化之前。最花时间在哪里? – MrSmith42 2013-03-21 20:41:43