由于我们的大学课程,过去几个月我一直在使用纯 C 进行编码。我编写的程序非常小并且不需要资源。因此,使用 gcc 进行编译几乎是瞬时过程(迄今为止我的“最大”程序需要 40 毫秒)。
最近,我参加了当地的一场比赛,显然 C++ 是常态,所以我开始练习。尽管我的程序仍然非常小(甚至不到半 kB),但我注意到使用 g++ 编译一直几乎像是 0.2 秒的暂停,然后是我习惯使用 gcc 的瞬时编译。
这是我当前正在测试的代码:
//#include <bits/stdc++.h> // I commented this out thinking that maybe the problem was due to too many header files being included
#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>
using namespace std; // I know this is kind of a bad practice but I've been told it's recommended in competitions for ease of writing
int mex(vector<int> arr, vector<int> subarr) {
int min = INT_MAX;
for (auto i : arr) {
// If i doesn't exist in subarr
if (find(subarr.begin(), subarr.end(), i) == subarr.end()) {
if (i < min) {
min = i;
}
}
}
return min;
}
int main () {
vector<int> a = {0,1,2,3,4,5};
vector<int> suba = {0, 1,3,4};
cout << mex(a, suba) << endl;
return 0;
}
编译耗时 240 毫秒。 这是 g++ 的
ftime-report
:
Time variable usr sys wall GGC
phase setup : 0.00 ( 0%) 0.00 ( 0%) 0.00 ( 0%) 1562k ( 2%)
phase parsing : 0.16 ( 84%) 0.13 ( 87%) 0.29 ( 85%) 60M ( 83%)
phase lang. deferred : 0.01 ( 5%) 0.01 ( 7%) 0.02 ( 6%) 5818k ( 8%)
phase opt and generate : 0.02 ( 11%) 0.01 ( 7%) 0.03 ( 9%) 5468k ( 7%)
|name lookup : 0.05 ( 26%) 0.02 ( 13%) 0.03 ( 9%) 2550k ( 3%)
|overload resolution : 0.01 ( 5%) 0.00 ( 0%) 0.02 ( 6%) 6891k ( 9%)
callgraph construction : 0.01 ( 5%) 0.00 ( 0%) 0.01 ( 3%) 1448k ( 2%)
df scan insns : 0.01 ( 5%) 0.00 ( 0%) 0.00 ( 0%) 4128 ( 0%)
preprocessing : 0.01 ( 5%) 0.05 ( 33%) 0.05 ( 15%) 1805k ( 2%)
parser (global) : 0.03 ( 16%) 0.02 ( 13%) 0.07 ( 21%) 16M ( 23%)
parser struct body : 0.00 ( 0%) 0.03 ( 20%) 0.03 ( 9%) 11M ( 15%)
parser function body : 0.03 ( 16%) 0.00 ( 0%) 0.03 ( 9%) 3231k ( 4%)
parser inl. func. body : 0.01 ( 5%) 0.02 ( 13%) 0.01 ( 3%) 1474k ( 2%)
parser inl. meth. body : 0.01 ( 5%) 0.00 ( 0%) 0.03 ( 9%) 5790k ( 8%)
template instantiation : 0.07 ( 37%) 0.02 ( 13%) 0.08 ( 24%) 19M ( 27%)
constant expression evaluation : 0.00 ( 0%) 0.00 ( 0%) 0.01 ( 3%) 85k ( 0%)
expand : 0.00 ( 0%) 0.01 ( 7%) 0.00 ( 0%) 367k ( 0%)
integrated RA : 0.00 ( 0%) 0.00 ( 0%) 0.00 ( 0%) 2092k ( 3%)
LRA non-specific : 0.00 ( 0%) 0.00 ( 0%) 0.01 ( 3%) 14k ( 0%)
symout : 0.01 ( 5%) 0.00 ( 0%) 0.00 ( 0%) 6907k ( 9%)
rest of compilation : 0.00 ( 0%) 0.00 ( 0%) 0.01 ( 3%) 212k ( 0%)
TOTAL : 0.19 0.15 0.34 73M
我在 Ubuntu 22.04 上使用 gcc 和 g++ 版本 11.4.0。
这是正常现象吗? g++ 通常比 gcc 慢得多吗?还是我的电脑存在根本问题?
是的,这是正常的。 C++ 语言比 C 语言复杂得多,标准头文件中还有更多内容。
企业级项目可能需要数小时才能构建,所以很高兴您的项目只需要 0.2 秒!
是的,根据我的经验,这很常见,因为 C++ 有很多功能和更复杂的语法。
如果您的代码不使用任何 C++ 功能,则编译时间可能几乎相同,但使用 C++ 会引入更多检查和逻辑,从而增加过程的复杂性。