gpt4 book ai didi

c++ - 是否允许 C++ 优化器跨函数调用移动语句?

转载 作者:IT老高 更新时间:2023-10-28 22:36:45 26 4
gpt4 key购买 nike

注意:这里根本没有多线程。刚刚优化了单线程代码。

函数调用 introduces a sequence point . (显然。)

是否允许编译器(如果优化器内联函数) 允许在函数指令之前/之后移动/混合任何指令? (只要它可以明显地“证明”没有可观察到的效果。)


说明背景:

现在,有一个 nice article wrt。一个 C++ 的基准测试类,作者在其中声明:

The code we time won’t be rearranged by the optimizer and will always lie between those start / end calls to now(), so we can guarantee our timing will be valid.

我问他怎么能确定,尼克回答说:

You can check the comment in this answer https://codereview.stackexchange.com/a/48884. I quote : “I would be careful about timing things that are not functions because of optimizations that the compiler is allowed to do. I am not sure about the sequencing requirements and the observable behavior understanding of such a program. With a function call the compiler is not allowed to move statements across the call point (they are sequenced before or after the call).”

What we do is basically abstract the callable (function, lambda, block of code surrounded by lambda) and have a signle call callable(factor) inside the measure structure that acts as a barrier (not the barrier in multithreading, I believe I convey the message).

我对此不太确定,尤其是引用:

With a function call the compiler is not allowed to move statements across the call point (they are sequenced before or after the call).

现在,我一直认为,当优化器内联某个函数时(在(简单)基准测试场景中很可能是这种情况),只要不影响它,它就可以自由地重新排列它喜欢的任何东西可观察到的行为。

也就是说,就语言/优化器而言,这两个片段完全相同:

void f() {
// do stuff / Multiple statements
}

auto start = ...;
f();
auto stop = ...;

对比

auto start = ...;
// do stuff / Multiple statements
auto stop = ...;

最佳答案

Now, I was always under the impression that when an optimizer inlines some function (which may very well be the case in a (simple) benchmark scenario), it is free to rearrange whatever it likes as long as it does not affect observable behavior.

绝对是。理论上,优化器甚至不需要内联它。

但是,计时函数是可观察到的行为——具体来说,它们是系统部分的 I/O。如果以与其他 I/O 调用不同的顺序执行,优化器无法知道 I/O 会产生相同的结果(显然不会),这可能包括不明显的事情,例如可以调用系统调用的内存分配调用获取他们的内存。

这基本上意味着,总的来说,对于大多数函数调用,优化器无法进行大量重新安排,因为可能涉及大量无法推理的状态。

此外,优化器无法真正知道重新安排函数调用实际上会使代码运行得更快,并且会使调试变得更加困难,因此他们没有很大的动力去搞砸按照程序规定的顺序。

基本上,理论上优化器可以做到这一点,但实际上不会,因为这样做将是一项艰巨的任务,不会带来太多好处。

只有当您的基准测试相当琐碎或几乎完全由整数加法等原始操作组成时,您才会遇到这样的情况——在这种情况下,您无论如何都需要检查程序集。

关于c++ - 是否允许 C++ 优化器跨函数调用移动语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29593156/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com