同一段代码用VS和g++编译器时间对比
代码示例
简单的排序算法
#include<iostream>
#include<algorithm>
#include<chrono>
#include<cstdlib>
#include<cstring>
#include<memory>
#include<random>
#include<vector>
using namespace std;
using chrono::duration_cast;
using chrono::milliseconds;
using chrono::system_clock;
// Comparison function for substring sort
bool compare(const char* s1, const char* s2, unsigned int l) {
if (s1 == s2) return false;
for (unsigned int i1 = 0, i2 = 0; i1 < l; ++i1, ++i2) {
if (s1[i1] != s2[i2]) return s1[i1] > s2[i2];
}
return false;
}
int main() {
constexpr unsigned int L = 12334611, N = 66941111;
unique_ptr<char[]> s(new char[L]);
vector<const char*> vs(N);
size_t count = 0;
system_clock::time_point t1 = system_clock::now(); // 这里是C++的计时函数
sort(vs.begin(), vs.end(),
[&](const char* a, const char* b) {
++count;
return compare(a, b, L);
});
cout << "hello, C++" << endl;
system_clock::time_point t2 = system_clock::now();
cout << "Sort time: " << duration_cast<milliseconds>(t2 - t1).count() << "ms (" << count << " comparisons)" << endl;
return 0;
}
使用VS2022计算结果
使用vscode & g++编译结果
甚至unsigned int 和 int作为循环变量的时候,计算时间也有差距;但同时我们可以看出,函数的调用次数是一样的。
unsigned int:
int: