I needed to sort a lot of small arrays of 8 floats. I originally used std :: sort, but I'm not happy with my performance, I tried the replacement comparison algorithm: http://pages.ripco.net/~jgamble/nw.html
test code is as follows:
template <typename T>
bool PredDefault(const T &a, const T &b) {return a > b;}
template <typename T>
bool PredDefaultReverse(const T &a, const T &b) {return a < b;}
template <typename T>
void Sort8(T* Data, bool(*pred)(const T &a, const T &b) = PredDefault) {
#define Cmp_Swap(a, b) if (pred(Data[a], Data[b])) {T tmp = Data[a]; Data[a] = Data[b]; Data[b] = tmp;}
Cmp_Swap(0, 1); Cmp_Swap(2, 3); Cmp_Swap(4, 5); Cmp_Swap(6, 7);
Cmp_Swap(0, 2); Cmp_Swap(1, 3); Cmp_Swap(4, 6); Cmp_Swap(5, 7);
Cmp_Swap(1, 2); Cmp_Swap(5, 6); Cmp_Swap(0, 4); Cmp_Swap(3, 7);
Cmp_Swap(1, 5); Cmp_Swap(2, 6);
Cmp_Swap(1, 4); Cmp_Swap(3, 6);
Cmp_Swap(2, 4); Cmp_Swap(3, 5);
Cmp_Swap(3, 4);
}
int lastTick;
int tick() {
int hold = lastTick;
lastTick = GetTickCount();
return lastTick - hold;
}
int main()
{
vector<vector<float>> rVec(1000, vector<float>(8));
for (auto &v : rVec) {
v[0] = ((float)rand()) * 0.001;
v[1] = ((float)rand()) * 0.001;
v[2] = ((float)rand()) * 0.001;
v[3] = ((float)rand()) * 0.001;
v[4] = ((float)rand()) * 0.001;
v[5] = ((float)rand()) * 0.001;
v[6] = ((float)rand()) * 0.001;
v[7] = ((float)rand()) * 0.001;
}
system("PAUSE");
tick();
for (int n = 0; n < 50000; n++)
for (int j = 0; j < rVec.size(); j++) {
std::sort(rVec[j].begin(), rVec[j].end(), PredDefault<float>);
std::sort(rVec[j].begin(), rVec[j].end(), PredDefaultReverse<float>);
}
cout << "\nTime: " << tick() << "\n";
system("PAUSE");
return 1;
}
add / remove comment labels when testing one or the other.
I did not expect much, but the difference is 10 times in favor of sorting (testing performed in the release configuration on vs2012 with power saving turned off). Results are also checked. It is right?