CL和G 编译器之间的差异


#include <iostream>
#include <algorithm>
#include <vector>
#include <chrono>
template<class Resolution = std::chrono::milliseconds>
class ExecutionTimer {
public:
    using Clock = std::conditional_t<std::chrono::high_resolution_clock::is_steady,
        std::chrono::high_resolution_clock,
        std::chrono::steady_clock>;
    ExecutionTimer() = default;
    ~ExecutionTimer() {
        std::cout
            << "Elapsed: "
            << std::chrono::duration_cast<Resolution>(Clock::now() - mStart).count()
            << std::endl;
    }
private:
    Clock::time_point mStart = Clock::now();
};
int main() {
    ExecutionTimer<> timer;
    std::vector<int> v(50000000);
    std::sort(std::begin(v), std::end(v));
    return 0;
}

我试图用2个不同的编译器编译上述C 代码,并将两个.EXE文件的运行时间差异为

我使用环境变量

    " c: program Files(x86) Microsoft Visual Studio 2017 community community vc tools msvc MSVC 14.10.25017 bin bin hostx64 x64 x64 x64"

CL  ->  cl /ehsc Benchmark.cpp
        364 (ms)
g++ ->  g++ -std=c++17 Benchmark.cpp -o bench17
        16565 (ms)

有人可以告诉我为什么有很大的区别?

默认情况下,G 根本不执行任何优化。对于使用标准模板的代码,这尤其有问题,这些模板几乎在预编译的标准库之外完全实现,因此缺乏优化非常可见。

我没有Microsoft编译器可以测试,但是在我的系统上,启用-O2将执行时间从25秒钟以上降低到不到一秒钟。

相关内容

最新更新