I wrote such a test -
std::vector<int> test_vector;
for (int i = 0; i < 100000000; ++i) {
test_vector.push_back(i);
}
QElapsedTimer timer;
timer.start();
std::sort(test_vector.begin(),test_vector.end(), [](int a, int b) { return a < b; });
qDebug() << "The slow operation took" << timer.elapsed() << "milliseconds";
qDebug() << "The slow operation took" << timer.nsecsElapsed() << "nanoseconds";
here i start re-sorting and the result
The slow operation took 4091 milliseconds
The slow operation took 4091842000 nanoseconds
but when I changed
std::sort(test_vector.begin(),test_vector.end(), [](int a, int b) { return a > b; });
result
The slow operation took 2867 milliseconds
The slow operation took 2867591800 nanoseconds
i tested on Qt_5_12_3_MinGW_64_bit-Release , and can't understand why in reverse sorting is faster, than re-sorting?
Resolved!
I tested the same example on Qt_5_12_3_MSVC2017_64bit and the issue is resolved, the problem was in MinGW_64
However, I still have a question, why if I sort the vector into a feed all the elements of 10,
#include <chrono>
#include<iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> test_vector;
for (int i = 0; i < 100000000; ++i) {
test_vector.push_back(10);
}
auto begin = chrono::high_resolution_clock::now();
std::sort(test_vector.begin(), test_vector.end(), [](int a, int b) { return a < b; });
auto end = std::chrono::high_resolution_clock::now();
auto dur = end - begin;
auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(dur).count();
std::cout << ms << endl;
return 0;
}
result 167 milliseconds,
and re-sorting 2553 milliseconds
for (int i = 0; i < 100000000; ++i) {
test_vector.push_back(i);
}