pow()函數和直接用乘法的性能比較——以camel函數為例


最近在用C++編寫模擬退火算法,並用Camel函數對算法的性能進行測試,由於模擬退火算法的特性,在程序運行中需要非常多次地計算Camel函數的值。

首先介紹一下Camel函數:

  

函數的表達式中有一個x的四次冪,多個x、y的平方項,最早是想用pow()函數來計算, 后來又直接用乘法的表達式來計算,不知道哪個會快一些,這個對於SA算法的性能還是蠻關鍵的,於是做了個簡單的測試,具體看代碼了:

Func1:全部用乘法;

Func2:四次冪用pow(),其余用乘法;

Func3:全部用pow()函數來計算;

#include <iostream>
#include <cmath>
#include <ctime>
#include <vector>
using namespace std;

//Func1:全部用乘法
double Func1(const vector<double> &state)
{
    double x = state[0];
    double y = state[1];
    double f = (4 - 2.1*x*x + x*x*x*x / 3.0)*x*x + x*y + (-4 + 4.0 * y*y)*y*y;
    return  f;
    
}
//Func2:四次冪用pow(),其余用乘法
double Func2(const vector<double> &state)
{
    double x = state[0];
    double y = state[1];
    double f;
    f = (4 - 2.1*x*x + pow(x,4) / 3.0)*x*x + x*y + (-4 + 4.0 * y*y)*y*y;
    return f;
}
//Func3:全部用pow()函數來計算
double Func3(const vector<double> &state)
{
    double x = state[0];
    double y = state[1];
    double f;
    f = (4 - 2.1*pow(x, 2) + pow(x, 4) / 3.0)*pow(x, 2) + x*y + (-4 + 4.0 * pow(y, 2))*pow(y, 2);
    return f;
}

int main()
{
    vector<double> initialState(2);
    initialState[0] = 0.0898;
    initialState[1] = -0.7126;
    
    clock_t start, end;

    //Func1的測試
    int i = 10000000;
    start = clock();
    while (i--)
    {
        Func1(initialState);
    }
    end = clock();
    cout << "Func1 cost: " << (double)(end - start) / CLOCKS_PER_SEC << endl;

    //Func2的測試
    int j = 10000000;
    start = clock();
    while (j--)
    {
        Func2(initialState);
    }
    end = clock();
    cout << "Func2 cost: " << (double)(end - start) / CLOCKS_PER_SEC << endl;

    //Func3的測試
    int k = 10000000;
    start = clock();
    while (k--)
    {
        Func3(initialState);
    }
    end = clock();
    cout << "Func3 cost: " << (double)(end - start) / CLOCKS_PER_SEC << endl;

    getchar();
    return 0;
}

結果如下:

可以看到,在運行10000000次后,計算速度的差距就體現出來了,使用乘法的速度最快,大約只有第三個函數的35%

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM