假设我有这样的代码,称之为版本 1:
while (some_condition) {
// .. work that may trigger rare_condition ...
if (rare_condition) {
// .. rare work here ..
continue;
}
// .. work that may trigger rare_condition ...
if (rare_condition) {
// .. rare work here ..
continue;
}
// .. more work
}
Run Code Online (Sandbox Code Playgroud)
假设这两种情况下的“稀有作品”是相同的。我们可以等效地编写版本 2:
while (some_condition) {
// .. work that may trigger rare_condition ...
if (rare_condition) {
goto rare_work;
}
// .. work that may trigger rare_condition ...
if (rare_condition) {
goto rare_work; …Run Code Online (Sandbox Code Playgroud) 这是一个对任何平台、语言或编译器都开放的天真的一般性问题。虽然我最好奇的是 Aarch64、C++、GCC。
当在依赖于 I/O 状态的程序流中编写不可避免的分支时(编译器无法预测),并且我知道一种状态比另一种状态更有可能,我如何向编译器表明这一点?
这是否更好
if(true == get(gpioVal))
unlikelyFunction();
else
likelyFunction();
Run Code Online (Sandbox Code Playgroud)
比这个?
if(true == get(gpioVal))
likelyFunction(); // performance critical, fill prefetch caches from this branch
else
unlikelyFunction(); // missed prediction not consequential on this branch
Run Code Online (Sandbox Code Playgroud)
如果通信协议使更有可能或临界值为真(高)或假(低),这是否有帮助?
我试图查看 == 和 != 之间的速度差异,我突然想到 if-else 中的顺序可能并不重要。纯粹从逻辑上讲,如果您需要测试一个条件,并且只有两个选项,那么跳到“if”部分或“else”部分应该没有任何区别。
至少这是我的思考过程,对它的实际运作方式一无所知。这就是你进来的地方。
这是一些代码来显示我想要选择的内容:
if (x == 10)
// do stuff. this will be true 20% of the time
else
// do frequent stuff
Run Code Online (Sandbox Code Playgroud)
if (x != 10)
// do frequent stuff 80% of time
else
// do other stuff 20% of the time
Run Code Online (Sandbox Code Playgroud)
请帮忙
具体来说,我问的是双“!” 在 __built_in 的参数中。
按照“C”语言,它是双重否定吗?
我想知道下面两个不同的代码是否比另一个更好。它们执行相同的功能。我认为在实现此代码时,您会希望 if 语句包含更频繁出现的参数。
选项1
if(hoursWorked <= 40){
workedOvertime = 0;
}
else{
workedOvertime = 1;
}
Run Code Online (Sandbox Code Playgroud)
选项#2
if(hoursWorked > 40){
workedOvertime = 1;
}
else{
workedOvertime = 0;
}
Run Code Online (Sandbox Code Playgroud) c ×4
gcc ×2
optimization ×2
assembly ×1
c++ ×1
clang ×1
gnu ×1
if-statement ×1
performance ×1
x86-64 ×1