问题描述
限时送ChatGPT账号..在回答这个问题之前,请考虑分支预测.
Please consider the branch prediction too before answering this question.
我有一些场景,我可以在函数指针的帮助下用对函数的调用替换条件语句.类似这样的事情.(对于类似的场景,您可以考虑基于组件的编程而不是继承)
I have some scenarios where i can replace a conditional statement with a call to a function with the help of function pointer.Some thing like this. (you can think of component based programming over inheritance for a similar type of senario)
class Shape
{
float Area()
{
if(type == SQUARE)
{
return length*length;
}
else if(type == RECTANGLE)
{
return length*breadth;
}
}
}
同一个类可以这样写.
class Shape
{
void SetAreaFunction(void *funcptr)//this function is used to set the current AreaFunc
{
CurrentAreaFunc = funcptr ;//this holds the pointer to current area func
}
float SqauareArea();//this will return square area
float RectangleArea();//this will return rectangle area
float Area()
{
currentAreaFunc();
}
}
如果您考虑上述情况,两者都会达到相同的结果.但是,我正在考虑性能开销.在第二种情况下,我通过调用函数来避免出现分支预测问题.
IF you consider the above cases, both achieves same results.But, I'm thinking about the performance overhead.In the second case I'm avoiding having branch prediction problem by having a function call.
现在让我知道在这种情况下哪个是更好的实践和更好的优化代码".(顺便说一句,我不喜欢过早的优化是万恶之源"的说法,因为优化有它的好处,所以我确实考虑优化我的代码!)
Now let me know which is the better practice and 'better optimized code' in this kind of senarios.(btw, I don't like the statement "Pre-mature optimization is root of all evil" as, optimization has its benefits so i do consider optimizing my code!)
P.S:我不介意是否有人详细概述分支预测有多糟糕",即使在汇编代码中也是如此.
P.S: I don't mind if any one give a detailed overview about 'how bad branch prediction can be" even in assembly code.
更新:在分析之后(类似上面的代码),
如果 Condition 在这种 senario 中成功.有人可以给出原因吗?由于没有分支代码,因此可以预取函数调用代码,对吗?但在这里它看起来是另一种方式......分支代码获胜!:O在 Intel Mac Osx、GCC O3/Os 优化上进行了分析.
Update: After profiling (similar kind of above code),
If Condition succeeded in this kind of senario.Can any one give a reason for this?
Functional call code can be prefetched as there is no Branching code right? But here its looks the other way..branching code wins! :O
Profiled on Intel Mac Osx,GCC O3/Os optimisation.
推荐答案
您用间接语句替换了 if 语句.
You replaced an if statement with an indirection.
您的 if 语句和间接访问都需要内存访问.
Both your if statement, and the indirection requires memory access.
但是,if 会导致短跳转 - 这可能不会使管道无效,而间接寻址可能会使管道无效.
However, the if will result in a short jump - which will probably won't invalidate the pipeline, while the indirection may invalidate the pipeline.
另一方面,间接是跳转,而if语句是条件跳转.分支预测器可能会丢失.
On the other hand, the indirection is a jump, while the if statement is a conditional jump. The branch predictor may miss.
如果不进行测试,很难判断哪个更快.我预测 if 语句会获胜.
It is hard to tell which is faster without testing it. I predict that the if statement will win.
请分享您的结果!
这篇关于哪个更快?函数调用还是条件 if 语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
更多推荐
[db:关键词]
发布评论