我很好奇并做了一个小基准测试来确定原始类型(如
我创建了一个模板类
我对结果感到非常惊讶,发现我的
相对而言,使用类Var比使用floats快6-7%,使用int约为3%。
我还将测试向量长度从原始的1000增加到1000万,并且结果仍然一致并且更有利于使用类。
int
或 float
)和用户自定义类型之间的性能差异。我创建了一个模板类
Var
,创建了一些内联算术运算符。测试包括对原始类型和 Var
向量执行此循环:for (unsigned i = 0; i < 1000; ++i) {
in1[i] = i;
in2[i] = -i;
out[i] = (i % 2) ? in1[i] + in2[i] : in2[i] - in1[i];
}
我对结果感到非常惊讶,发现我的
Var
类在大多数情况下比 int 更快,平均循环时间减少了约 5700 纳秒。在 3000 次运行中,int 比 Var
快 11 次,而 Var
比 int 快 2989 次。在使用 float
时也有类似的结果,Var
比 float 快 15100 纳秒,在 2991 次运行中更快。
难道原始类型不应该更快吗?
编辑:编译器是 rather ancient mingw 4.4.0,构建选项是 QtCreator 的默认选项,没有进行优化。
qmake call: qmake.exe C:\...\untitled15.pro -r -spec win32-g++ "CONFIG+=release"
好的,发布完整源代码,平台为64位Win7,4 GB DDR2-800,Core2Duo @ 3Ghz。
#include <QTextStream>
#include <QVector>
#include <QElapsedTimer>
template<typename T>
class Var{
public:
Var() {}
Var(T val) : var(val) {}
inline T operator+(Var& other)
{
return var + other.value();
}
inline T operator-(Var& other)
{
return var - other.value();
}
inline T operator+(T& other)
{
return var + other;
}
inline T operator-(T& other)
{
return var - other;
}
inline void operator=(T& other)
{
var = other;
}
inline T& value()
{
return var;
}
private:
T var;
};
int main()
{
QTextStream cout(stdout);
QElapsedTimer timer;
unsigned count = 1000000;
QVector<double> pin1(count), pin2(count), pout(count);
QVector<Var<double> > vin1(count), vin2(count), vout(count);
unsigned t1, t2, pAcc = 0, vAcc = 0, repeat = 10, pcount = 0, vcount = 0, ecount = 0;
for (int cc = 0; cc < 5; ++cc)
{
for (unsigned c = 0; c < repeat; ++c)
{
timer.restart();
for (unsigned i = 0; i < count; ++i)
{
pin1[i] = i;
pin2[i] = -i;
pout[i] = (i % 2) ? pin1[i] + pin2[i] : pin2[i] - pin1[i];
}
t1 = timer.nsecsElapsed();
cout << t1 << endl;
timer.restart();
for (unsigned i = 0; i < count; ++i)
{
vin1[i] = i;
vin2[i] = -i;
vout[i] = (i % 2) ? vin1[i] + vin2[i] : vin2[i] - vin1[i];
}
t2 = timer.nsecsElapsed();
cout << t2 << endl;;
pAcc += t1;
vAcc += t2;
}
pAcc /= repeat;
vAcc /= repeat;
if (pAcc < vAcc) {
cout << "primitive was faster" << endl;
pcount++;
}
else if (pAcc > vAcc) {
cout << "var was faster" << endl;
vcount++;
}
else {
cout << "amazingly, both are equally fast" << endl;
ecount++;
}
cout << "Average for primitive type is " << pAcc << ", average for Var is " << vAcc << endl;
}
cout << "int was faster " << pcount << " times, var was faster " << vcount << " times, equal " << ecount << " times, " << pcount + vcount + ecount << " times ran total" << endl;
}
相对而言,使用类Var比使用floats快6-7%,使用int约为3%。
我还将测试向量长度从原始的1000增加到1000万,并且结果仍然一致并且更有利于使用类。