前言
GCC:你没写错,但是我优化出锅了(第二期 GCC 9.3.0)
算是一个补充吧。
起因
NOIP 考前水一期用来加 RP,祝各位 RP++。
关于 GCC 和 GNU
使用 $ 符号作为变量名字(#注意、#bug、#GCC 4.9.2)
好消息:我们现在已知在后续 GCC 版本中该 bug 已经修复,NOI Linux 2.0 上也没有什么显示的问题。
未知的风险:尚不明确这么用会导致什么结果,作为保险,尽量不要在这个版本中使用 $ 作为变量名。
这个并不是非法的,这个是属于 GNU 扩展,正常来说没有什么问题——但是,在 GCC 4.9.2 中使用 $ 作为变量名可能会导致编译器的问题。
我们观察一下代码:
long long $;
int main() {
return $;
}在 Dev-c++ 5.11 中如果你编译后其实可以正常运行,但是你如果留意下面的话你会发现还会有信息:
C:\Users\PC\AppData\Local\Temp\ccqWurJg.s: Assembler messages:
C:\Users\PC\AppData\Local\Temp\ccqWurJg.s:22: Error: illegal immediate register operand (%rip)这个提示是生成的汇编代码有问题,但是我们的代码没有问题,原因就是 GGC 的代码出 bug 了!
众所周知,在 AT&T 汇编语法(GCC 在 Linux 等平台默认使用的格式)中,$ 是一个保留前缀,专门用来表示“立即数”;但是如果使用 $ 作为变量名,就可能解析错误,比如汇编文件(.s 后缀)中可能会有这样无法正确解析的代码 $(%rip)。
我们可以使用传统异能导出一下汇编就明白了:
g++.exe -S cs.cpp -o output.s.s 文件
.file "cs.cpp"
.globl $
.bss
.align 8
$:
.space 8
.def __main; .scl 2; .type 32; .endef
.text
.globl main
.def main; .scl 2; .type 32; .endef
.seh_proc main
main:
.LFB0:
pushq %rbp
.seh_pushreg %rbp
movq %rsp, %rbp
.seh_setframe %rbp, 0
subq $32, %rsp
.seh_stackalloc 32
.seh_endprologue
call __main
movq $(%rip), %rax
addq $32, %rsp
popq %rbp
ret
.seh_endproc
.ident "GCC: (tdm64-1) 4.9.2"
-O2 的递归展开导致的 MLE(#注意、#bug、#GCC 9.3.0)
坏消息:这是一个 bug,在后续版本中被修复,但是 NOI Linux 2.0 并没有修复。(检测方法在下面)
很久之前就看到了这篇文章 CSP-S2025 游记:没人告诉我 NOI Linux 有编译器 bug 啊?,最近闲的去稍微了解了一下这个 bug。
这个算是经典了,不过我可能需要纠正一些可能错误的部分:
- -O2 的递归内联默认只展开 层,并不会知道你的递归实际上有多少层。
- 这里实际上的原因是因为
query函数被内联进入函数dfs1,之后导致dfs1的栈帧变大(32B -> 976B)然后乘上递归深度就爆了。
什么是栈帧
栈帧(Stack Frame),也称为过程活动记录(Activation Record),是函数(过程)在被调用时,于程序调用栈上动态分配的一块连续内存区域。它封装了一次函数调用所需的全部私有运行环境。可以将调用栈想象成一摞盘子,每发生一次函数调用,就在顶端放上一个新盘子;这个“盘子”就是栈帧,函数执行完毕后,它会被从顶端取走(弹出)。
简单来说,栈帧就是递归中一层占用的连续内存空间,所以我们有:
- 当前递归深度 = 当前调用栈上该递归函数的活跃栈帧数
- 最大递归深度 = 峰值活跃栈帧数
由于 -O2 把 query 函数进行了展开,再加上 -O2 的内联导致把 dfs1 的栈帧撑大,再乘上递归深度,于是就爆炸了。
测试栈帧的方法(#方法、#技巧)
我们有编译选项可以测试栈帧(但是并不能测试动态空间,这个是静态的,对于测试空间的方法在后面):
g++ name -std=c++14 -O2 -fstack-usage -o name上述命令会生成一个名为 name.su 的文件。
在 NOI Linux 2.0 中的测试结果如下:
完整内容
name.cpp:39:19:void __tcf_1(void*) 32 static
name.cpp:39:13:void __tcf_0(void*) 32 static
name.cpp:63:13:int Segment_Tree::query(int, int, int, int) 16 static
name.cpp:7:12:int read() 32 static
name.cpp:14:13:void write(int) 32 static
name.cpp:42:13:void dfs0(int) 32 static
name.cpp:56:14:void Segment_Tree::add(int&, int, int, int, int, int) 96 dynamic,bounded
name.cpp:74:13:void dfs1(int) 976 dynamic,bounded
stl_tree.h:1912:5:void std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_erase(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_Link_type) [with _Key = std::pair<int, int>; _Val = std::pair<const std::pair<int, int>, int>; _KeyOfValue = std::_Select1st<std::pair<const std::pair<int, int>, int> >; _Compare = std::less<std::pair<int, int> >; _Alloc = std::allocator<std::pair<const std::pair<int, int>, int> >] 32 static
stl_map.h:300:7:std::map<_Key, _Tp, _Compare, _Alloc>::~map() [with _Key = std::pair<int, int>; _Tp = int; _Compare = std::less<std::pair<int, int> >; _Alloc = std::allocator<std::pair<const std::pair<int, int>, int> >] 8 static
stl_tree.h:2572:5:std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::find(const _Key&) const [with _Key = std::pair<int, int>; _Val = std::pair<const std::pair<int, int>, int>; _KeyOfValue = std::_Select1st<std::pair<const std::pair<int, int>, int> >; _Compare = std::less<std::pair<int, int> >; _Alloc = std::allocator<std::pair<const std::pair<int, int>, int> >] 8 static
vector.tcc:426:7:) [with _Args = {std::array<int, 3>}; _Tp = std::array<int, 3>; _Alloc = std::allocator<std::array<int, 3> >] 96 static
vector.tcc:109:7:) [with _Args = {std::array<int, 3>}; _Tp = std::array<int, 3>; _Alloc = std::allocator<std::array<int, 3> >] 8 static
stl_tree.h:2090:5:std::pair<std::_Rb_tree_node_base*, std::_Rb_tree_node_base*> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_get_insert_unique_pos(const key_type&) [with _Key = std::pair<int, int>; _Val = std::pair<const std::pair<int, int>, int>; _KeyOfValue = std::_Select1st<std::pair<const std::pair<int, int>, int> >; _Compare = std::less<std::pair<int, int> >; _Alloc = std::allocator<std::pair<const std::pair<int, int>, int> >] 32 static
stl_tree.h:2192:5:std::pair<std::_Rb_tree_node_base*, std::_Rb_tree_node_base*> std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::_M_get_insert_hint_unique_pos(std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare, _Alloc>::const_iterator, const key_type&) [with _Key = std::pair<int, int>; _Val = std::pair<const std::pair<int, int>, int>; _KeyOfValue = std::_Select1st<std::pair<const std::pair<int, int>, int> >; _Compare = std::less<std::pair<int, int> >; _Alloc = std::allocator<std::pair<const std::pair<int, int>, int> >] 48 static
stl_tree.h:2457:7:) [with _Args = {const std::piecewise_construct_t&, std::tuple<const std::pair<int, int>&>, std::tuple<>}; _Key = std::pair<int, int>; _Val = std::pair<const std::pair<int, int>, int>; _KeyOfValue = std::_Select1st<std::pair<const std::pair<int, int>, int> >; _Compare = std::less<std::pair<int, int> >; _Alloc = std::allocator<std::pair<const std::pair<int, int>, int> >] 48 static
stl_map.h:490:7:std::map<_Key, _Tp, _Compare, _Alloc>::mapped_type& std::map<_Key, _Tp, _Compare, _Alloc>::operator[](const key_type&) [with _Key = std::pair<int, int>; _Tp = int; _Compare = std::less<std::pair<int, int> >; _Alloc = std::allocator<std::pair<const std::pair<int, int>, int> >] 48 static
name.cpp:92:5:int main() 160 static
name.cpp:175:1:cpp) 16 static
其中较为关键的是(截取):
name.cpp:42:13:void dfs0(int) 32 static
name.cpp:74:13:void dfs1(int) 976 dynamic,bounded
stl_tree.h:1912:5:void std::_Rb_tree<_Key, _Val, _KeyOfValue, _Compare,我们注意到 dfs1 的栈帧异常,这进一步表明了我们的理论是正确的。
关于 UB
这个 NOIP 考场上是有虚拟机的,一般测一下都没什么问题。
如果不太放心可以加一些参数:-Wall -Wextra。
在 NOI Linux 2.0 下我们有很多可用的参数(动态静态都有):
g++ -std=c++14 -O1 -g -fno-omit-frame-pointer \
-fsanitize=address,pointer-compare,pointer-subtract,undefined,bounds-strict,builtin,float-divide-by-zero,float-cast-overflow \
-fno-sanitize-recover=all \
-D_GLIBCXX_DEBUG -D_GLIBCXX_DEBUG_PEDANTIC \
-Wall -Wextra -Wshadow -Wformat=2 \
-Wduplicated-branches -Wduplicated-cond -Wnull-dereference -Wlogical-op \
-Warray-bounds=2 -Wstrict-overflow=2 -Wstack-usage=262144 -Wvla \
-o a_all a.cpp测速的话不要加 -fsanitize=pointer-compare,pointer-subtract。必须配合运行时 ASAN_OPTIONS=detect_invalid_pointer_pairs=2 才有效(单独是不报的)。
关于 gpof(#优化、#时间复杂度)
gprof 是一种插桩(Instrumentation)分析工具。它的工作方式是在编译阶段修改你的程序代码。
具体来说,当你使用 GCC 的 -pg 选项编译并链接程序时,编译器会在每个函数的入口插入一小段代码。当程序运行时,这段代码会记录下函数的调用关系、被调用的次数以及执行时间等信息。程序正常运行结束后,这些记录的数据会被写入一个名为 gmon.out 的文件中。
这个就是可以用来分析你的函数调用关系,函数调用次数之类的,用来卡卡常或者找程序热点还是好用的。
使用方法
你可以选择将 Dev-c++ 中的编译器配置(编译运行按键向右找默认 TMD-GCC 4.9.2 64-bit Release),然后切换为 TMD-GCC 4.9.2 64-bit Profiling 即可(这个时候编译选项已经不需要加入 -pg 了,因为在这个配置下会自动加入)。
然后在这个配置下编译运行程序后在同目录下会出现 gmon.out 的可执行文件,里面存贮着你代码的测试数据,接着在菜单栏点击运行,向下找到性能分析,然后点击后就能看到:
- 平面剖面图(Flat Profile)
- 调用图(Call Graph)
当然你也可以使用一下命令
gprof main.exe gmon.out来在终端显示,当然也可以重定向到文件内阅读:
gprof main.exe gmon.out > analysis.txt当然,gprof 还支持一些有用的选项来定制输出,例如 --demangle(还原 C++ 函数名,使其可读)和 -f function_name(只关注特定函数及其子函数的调用图)。(详见 Running gprof-GNAT User’s Guide)
解读方法
平面剖面图
平面剖面图是宏观视角,它按函数自身消耗的时间降序列出,让你清晰的看出耗时最长的函数。
一个典型的 Flat Profile 如下所示:
% cumulative self self total
time seconds seconds calls ms/call ms/call name
33.34 0.02 0.02 7208 0.00 0.00 open
16.67 0.03 0.01 244 0.04 0.12 offtime
16.67 0.04 0.01 8 1.25 1.25 memccpy| 列名 | 含义与解读 |
|---|---|
% time | 此函数自身执行时间占总运行时间的百分比。所有函数的百分比总和应接近 100%。 |
cumulative seconds | 累积秒数:本函数及其上方所有函数的 self seconds 之和。这是一个“滚动总和”。 |
self seconds | 自身秒数:这是最关键的指标,表示仅在该函数内部消耗的时间,不含其调用的子函数。Flat Profile 默认按此列降序排列。 |
calls | 函数被调用的总次数。若无法确定(如未用 -pg 编译),此列可能为空。 |
self ms/call | 自身毫秒/次:self seconds 除以 calls,即每次调用该函数自身的平均耗时。适合比较不同函数的单次执行效率。 |
total ms/call | 总毫秒/次:每次调用该函数及其所有子函数的平均总耗时。它揭示了函数作为“入口”的整体开销。 |
name | 函数名称。 |
调用图
调用图是微观视角,展示函数间的调用关系,并量化时间在调用链上的分布。它的用处就是可以找到主要耗时是在子函数而不是原函数的情况。
一个调用图片段如下:
index % time self children called name
0.00 0.05 1/1 main [2]
[1] 100.0 0.00 0.05 1 start [1]
0.00 0.05 1/1 main [2]
[2] 100.0 0.00 0.05 1 main [2]
0.00 0.05 1/1 report [3]每个条目(Entry) 由虚线分隔,对应一个函数,包含多行:
- 主行(Primary Line):方括号
[index]开头的那行,是该函数的摘要。 - 调用者行(Caller Lines):位于主行上方,说明“谁调用了本函数”。
- 被调用者行(Children Lines):位于主行下方,说明“本函数调用了谁”。
以 [2] main 条目为例:
- 主行
[2] 100.0 0.00 0.05 1 main [2]:% time:100.0%,main及其子函数占总时间的 100%。self:0.00 秒,main自身几乎不耗时。children:0.05 秒,其调用的子函数总耗时 0.05 秒。called:1 次,main被调用 1 次。
- 调用者行
0.00 0.05 1/1 main [2](在[1] start条目下):表示start调用了main1 次,这次调用中main及其子函数共耗时 0.05 秒。 - 被调用者行
0.00 0.05 1/1 report [3](在[2] main条目下):表示main调用了report1 次,report及其子函数共耗时 0.05 秒。
关于检测空间
我们没有办法便捷的监测动态空间比较赤石,但是在 NOI Linux 2.0 下我们存在 python 就很人类。
./a<in.txt >out.txt&while kill -0 $! 2>/dev/null;do grep -E 'VmPeak' /proc/$!/status;done|tail -1VmPeak 是看历史最大内存,当然还有一些别的参数
| 字段 | 含义 |
|---|---|
VmPeak / VmHWM | 虚拟内存 / 物理内存的峰值 |
VmSize / VmRSS | 当前虚拟内存 / 物理内存 |
VmData / VmStk | 堆 / 栈 |
Threads | 线程数 |
voluntary_ctxt_switches | 主动上下文切换次数 |
注意 VmPeak、VmHWM 是历史最大,其他都是瞬时值,所以到最后只会保留最后一次采样。
然后当然你也可以这样来限制内存
ulimit -v <大小(单位KB)>然后如果说你用上面的 VmPeak 测空间超时了,可以通过上述指令限制空间,然后跑 gdb 调试,让其中止在程序停止时。
一些乱七八糟的东西
有关于 fc 的冷知识
在我们比对大样例的时候有时候会因为文件过而不能完整进行人工比较,这时我们就可以用 windows 环境下的 fc 来进行比对。示例如下:
fc <文件名> <文件名>但是,有时候会因为我们找不到出错的具体位置导致很恼火。于是我们可以使用 \n 参数来输出行号。
fc /n <文件名> <文件名>当然 fc 有时候可能会因为同步之类的问题跑的很慢,如果你想使得两个文件完全相同(这里换行格式也要相同)就可以:
fc /b <文件名> <文件名>存在可能你输出每一行的行末空格会被认为非法的情况,这个有两种解决方法:
- 修改代码你可以这样
for(int i=1;i<=n;i++) cout<<i<<" \n"[i==n],原因就是"\n"被创建为临时字符串变量,然后就不输出掉行末空格。 - fc 中提供了忽略行首和行末空白的参数
/w。
最后
祝所有人 RP++,永不挂分。