如何在C++中优化简单的数值类型包装类?

Mic*_*bon 11 c++ optimization performance fixed-point

我试图用C++实现一个定点类,但我遇到性能问题.我已经将问题简化为浮点类型的简单包装,它仍然很慢.我的问题是 - 为什么编译器无法完全优化它?

'float'版本比'Float'快50%.为什么?!

(我使用Visual C++ 2008,测试了所有可能的编译器选项,当然是Release配置).

请参阅以下代码:

#include <cstdio>
#include <cstdlib>
#include "Clock.h"      // just for measuring time

#define real Float      // Option 1
//#define real float        // Option 2

struct Float
{
private:
    float value;

public:
    Float(float value) : value(value) {}
    operator float() { return value; }

    Float& operator=(const Float& rhs)
    {
        value = rhs.value;
        return *this;
    }

    Float operator+ (const Float& rhs) const
    {
        return Float( value + rhs.value );
    }

    Float operator- (const Float& rhs) const
    {
        return Float( value - rhs.value );
    }

    Float operator* (const Float& rhs) const
    {
        return Float( value * rhs.value );
    }

    bool operator< (const Float& rhs) const
    {
        return value < rhs.value;
    }
};

struct Point
{
    Point() : x(0), y(0) {}
    Point(real x, real y) : x(x), y(y) {}

    real x;
    real y;
};

int main()
{
    // Generate data
    const int N = 30000;
    Point points[N];
    for (int i = 0; i < N; ++i)
    {
        points[i].x = (real)(640.0f * rand() / RAND_MAX);
        points[i].y = (real)(640.0f * rand() / RAND_MAX);
    }

    real limit( 20 * 20 );

    // Check how many pairs of points are closer than 20
    Clock clk;

    int count = 0;
    for (int i = 0; i < N; ++i)
    {
        for (int j = i + 1; j < N; ++j)
        {
            real dx = points[i].x - points[j].x;
            real dy = points[i].y - points[j].y;
            real d2 = dx * dx + dy * dy;
            if ( d2 < limit )
            {
                count++;
            }
        }
    }

    double time = clk.time();

    printf("%d\n", count);
    printf("TIME: %lf\n", time);

    return 0;
}
Run Code Online (Sandbox Code Playgroud)

iam*_*ind 4

IMO,它与优化标志有关。我在 g++ linux-64 机器上检查了你的程序。没有任何优化,它会给出与您告诉的结果相同的结果50%

保持最大优化打开(即-O4)。两个版本都是一样的。打开优化并检查。