c++ - 一样的功能?使用 GMP(C++) 运行速度慢大约 10 倍

标签 c++ performance gmp mandelbrot

我用 C++ 编写了 Mandelbrot 缩放,但由于浮点不准确,缩放受到限制。这就是为什么我用 GMP 库重新编写了整个内容。

但现在我遇到了性能问题。我是 GMP 的新手,所以也许我只是搞砸了一些事情:

原代码如下:

int iterate(double xp, double yp, int iterations){
double length = 1;
double x = 0;
double y = 0;
double r;
for(int i = 0; i < iterations && length <= 2; i++){
    double xTemp = x;
    //calculate real part
    x = (x*x)+xp-(y*y);
    //calculate imaginary part
    y = 2*xTemp*y+yp;
    //calculate lenth
    length = sqrt(x*x+y*y);
    r = i+1;
}
if(length > 2)
    return r;
return 0;

与 GMP 具有相同的功能(我认为它是相同的),我添加了两个变量 temp 和 temp2 来存储用于计算的值,但这不应该使它慢 10 倍:

int iterateGMP(mpf_t xpGMP, mpf_t ypGMP, int iterations){
double r;

mpf_set_default_prec (20);

mpf_t length;
mpf_init(length);
mpf_set_d(length, 1);
mpf_t x;
mpf_init(x);
mpf_set_d(x, 0);
mpf_t y;
mpf_init(y);
mpf_set_d(y, 0);
mpf_t xTemp;
mpf_init(xTemp);
mpf_t TempGMP;
mpf_init(TempGMP);
mpf_t Temp2GMP;
mpf_init(Temp2GMP);


for(int i = 0; i < iterations && mpf_cmp_ui(length, 2)<0; i++){
    mpf_set(xTemp, x);

    //calculate real part
    mpf_mul(TempGMP, x, x);
    mpf_add(TempGMP, TempGMP, xpGMP);
    mpf_mul(Temp2GMP, y, y);
    mpf_sub(x, TempGMP, Temp2GMP);

    //calculate imaginary part
    mpf_mul(TempGMP, xTemp, y);
    mpf_mul_ui(TempGMP, TempGMP, 2);
    mpf_add(y, TempGMP, ypGMP);

    //calculate length
    mpf_mul(TempGMP, x, x);
    mpf_mul(Temp2GMP, y, y);
    mpf_add(TempGMP, TempGMP, Temp2GMP);
    mpf_sqrt(length, TempGMP);
    r = i+1;
}
if(mpf_cmp_ui(length, 2) > 0){
    return r;
}
return 0;

我希望有人能帮助我。

最佳答案

I added two variables, temp and temp2, to store values for calculation but this shouldn't make it 10 times slower

floatdouble 上的操作通常由硬件处理。而对 GMP 类型的操作由软件中的 GMP 库处理。

GMP 值也需要更多的内存来存储,而内存通常是瓶颈。

关于c++ - 一样的功能?使用 GMP(C++) 运行速度慢大约 10 倍,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35274375/

相关文章:

C++内联函数指针和模板函数设计

Jquery和内存

php - SQL语句的计算速度

linux - 在 R 中,使用 Ubuntu,尝试根据 GMP C lib 安装一个 lib,它找不到 GMP,但我安装了 GMP

c++ - 如何在 Windows 上为 Dev-C++ 安装 C++ 库

Xcode 中的 C++ 单例

c++ - 迭代器的模板参数 : function infers type when called?

c++ - 继承类中的比较运算符

python - 提高 numpy 映射操作的性能

c - GMP pow 中的溢出处理