C++で固定小数点クラスを実装しようとしていますが、パフォーマンスに問題があります。私は浮動小数点型の単純なラッパーに問題を減らしましたが、それはまだ遅いです。私の質問は - コンパイラが完全に最適化できないのはなぜですか?C++で単純な数値型ラッパークラスを最適化する方法は?
'float'バージョンは 'Float'より50%高速です。なぜ?!
(私はVisual C++ 2008を使用して、すべての可能なコンパイラのオプションをテストしました。
は、以下のコードを参照してください:
IMO#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;
}
最大限の最適化フラグをオンにしましたか?私はあなたがそれらをオンにすると魔法が起こっているのを見ました。 – iammilind
アセンブリを生成し、違いがどこにあるのか確認してください... –
すべてのメソッドを明示的に 'インライン'としてマークしようとする可能性があります –