g++优化选项

g++优化选项

对于下面的这段代码:

1
2
3
4
5
6
7
8
9
10
11
12
#include <iostream>
using namespace std;
int 
main()
{
    const int n = 1e9;
    for(int i = 0; i < n; ++i)
    {
        //~ nothing
    }
    return 0;
}

正常的编译命令:

1
$ g++ test.cpp -o test

用time测试运行时间:

1
time ./test

输出:

real	0m4.431s
user	0m4.068s
sys	0m0.012s

使用优化选项编译:

1
$ g++ test.cpp -o test -O2

此时的运行时间:

real	0m0.008s
user	0m0.000s
sys	0m0.004s

so amazing!
g++有四个级别的优化选项,分别对应于 -O1, -O2, -O3, -O4.

原文地址:https://www.cnblogs.com/lexus/p/3327965.html