为什么要使用__builtin_expect当一个简单的方法是使用的if-else [英] Why do we use __builtin_expect when a straightforward way is to use if-else

查看:253
本文介绍了为什么要使用__builtin_expect当一个简单的方法是使用的if-else的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我碰上了一个的#define 中,他们使用 __ builtin_expect

I came across a #define in which they use __builtin_expect.

<一个href=\"https://gcc.gnu.org/onlinedocs/gcc/Other-Builtins.html#index-g_t_005f_005fbuiltin_005fexpect-4159\"相对=nofollow> 说的文档:

您可以使用 __ builtin_expect 来提供支编译
  prediction信息。一般情况下,你应该preFER用实际
  天寒这种反馈( -fprofile弧),因为程序员
  出了名的坏predicting他们的程序实际上是如何执行。
  但是,也有在该数据难以收集应用

Built-in Function: long __builtin_expect (long exp, long c)

You may use __builtin_expect to provide the compiler with branch prediction information. In general, you should prefer to use actual profile feedback for this (-fprofile-arcs), as programmers are notoriously bad at predicting how their programs actually perform. However, there are applications in which this data is hard to collect.

返回的值是 EXP 的价值,这应该是一个整体
  前pression。内置的语义是预期
   EXP == c审核。例如:

The return value is the value of exp, which should be an integral expression. The semantics of the built-in are that it is expected that exp == c. For example:

      if (__builtin_expect (x, 0))
        foo ();


  
  

将表明,我们并不指望调用,因为我们期望 X 为零。

那么,为什么不直接使用:

So why not directly use:

                 if ( x != 0 ) {}
                 else foo( );

而不是复杂的语法

与期望?

instead of the complicated syntax with expect?

推荐答案

设想一下,将从中产生组装code:

Imagine the assembly code that would be generated from:

if (__builtin_expect(x, 0)) {
    foo();
    ...
} else {
    bar();
    ...
}

我想这应该是这样的:

I guess it should be something like:

  cmp   $x, 0
  jne   _foo
_bar:
  call  bar
  ...
  jmp   after_if
_foo:
  call  foo
  ...
after_if:

您可以看到,指令被安排在这样一个为了使情况下,precedes的情况下(相对于C code)。这可以利用CPU流水线更好,因为跳捶打已经取出的指令。

You can see that the instructions are arranged in such an order that the bar case precedes the foo case (as opposed to the C code). This can utilise the CPU pipeline better, since a jump thrashes the already fetched instructions.

在执行跳跃之前,它下面的指令(情况)都推到管道。因为情况下是不可能的,太跳跃的可能性不大,因此颠簸的管道是不可能的。

Before the jump is executed, the instructions below it (the bar case) are pushed to the pipeline. Since the foo case is unlikely, jumping too is unlikely, hence thrashing the pipeline is unlikely.

这篇关于为什么要使用__builtin_expect当一个简单的方法是使用的if-else的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆