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%

 

posted on 2015-12-30 20:18  三杯不醉  阅读(4585)  评论(0编辑  收藏  举报

导航