c – 优化Mandelbrot分形
发布时间:2020-12-16 07:21:20 所属栏目:百科 来源:网络整理
导读:这是一个以.ppm文件输出mandelbrot分形的代码.我该如何优化呢? #includebits/stdc++.husing namespace std;int findMandelbrot(double cr,double ci,int max_iterations){ int i = 0; double zr = 0.0,zi = 0.0; while (i max_iterations zr * zr + zi * zi
这是一个以.ppm文件输出mandelbrot分形的代码.我该如何优化呢?
#include<bits/stdc++.h> using namespace std; int findMandelbrot(double cr,double ci,int max_iterations) { int i = 0; double zr = 0.0,zi = 0.0; while (i < max_iterations && zr * zr + zi * zi < 4.0) { double temp = zr * zr - zi * zi + cr; zi = 2.0 * zr * zi + ci; zr = temp; ++i; } return i; } double mapToReal(int x,int imageWidth,double minR,double maxR) { double range = maxR - minR; return x * (range / imageWidth) + minR; } double mapToImaginary(int y,int imageHeight,double minI,double maxI) { double range = maxI - minI; return y * (range / imageHeight) + minI; } int main() { ifstream f("input.txt"); int imageWidth,imageHeight,maxN; double minR,maxR,minI,maxI; if (!f) { cout << "Could not open file!" << endl; return 1; } f >> imageWidth >> imageHeight >> maxN; f >> minR >> maxR >> minI >> maxI; ofstream g("output_image.ppm"); g << "P3" << endl; g << imageWidth << " " << imageHeight << endl; g << "255" << endl; double start = clock(); for (int i = 0; i < imageHeight; i++) { for (int j = 0; j < imageWidth; j++) { double cr = mapToReal(j,imageWidth,minR,maxR); double ci = mapToImaginary(i,maxI); int n = findMandelbrot(cr,ci,maxN); int r = ((int)sqrt(n) % 256); int gr = (2*n % 256); int b = (n % 256); g << r << " " << gr << " " << b << " "; } g << endl; if(i == imageHeight / 2) break; } cout << "Finished!" << endl; double stop = clock(); cout << (stop-start)/CLOCKS_PER_SEC; return 0; } 我一直到imageHeight / 2,因为在Photoshop中我可以复制另一半. 解决方法
所以这是热循环:
int i = 0; double zr = 0.0,zi = 0.0; while (i < max_iterations && zr * zr + zi * zi < 4.0) { double temp = zr * zr - zi * zi + cr; zi = 2.0 * zr * zi + ci; zr = temp; ++i; } return i; 我知道如何在快速CPU指令中实现非整数功率但它不会让你脱离绑定,因为它根本不适用于复数.也不会使用std :: complex帮助.您不会为非内联支付任何费用,当然也无法在您找到它们时应用优化.所以我能做的最好的就是: int i = max_iterations; double zr = 0.0,zi = 0.0; do { double temp = zr * zr - zi * zi + cr; zi = 2.0 * zr * zi + ci; zr = temp; } while (--i && zr * zr + zi * zi < 4.0) return max_iterations - i; 是的,我知道从循环中取出一个整数测试并没有太大的收获.我只发现了另一个优化器,你必须检查它是否真的更快: int i = max_iterations; double zr = 0.0,zi = 0.0; do { double tempr = zr * zr - zi * zi + cr; double tempi = zr * zi; zi = tempi + tempi + ci; zr = tempr; } while (--i && zr * zr + zi * zi < 4.0); return max_iterations - i; 这就是所有人. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |