我写了这样的测试-
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";
在这里我开始重新排序和结果
The slow operation took 4091 milliseconds
The slow operation took 4091842000 nanoseconds
但是当我改变
std::sort(test_vector.begin(),test_vector.end(), [](int a, int b) { return a > b; });
结果
The slow operation took 2867 milliseconds
The slow operation took 2867591800 nanoseconds
我在Qt_5_12_3_MinGW_64_bit-Release上进行了测试,无法理解为什么反向排序比重新排序更快?
我在Qt_5_12_3_MSVC2017_64bit上测试了相同的示例,问题已解决,问题出在MinGW_64中
但是,我仍然有一个问题,为什么我要将向量归类为供稿中所有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;
}
结果167毫秒,
并重新排序2553毫秒
for (int i = 0; i < 100000000; ++i) {
test_vector.push_back(i);
}