这是更快的(X小于0)或(X == -1)? [英] What is faster (x < 0) or (x == -1)?

查看:159
本文介绍了这是更快的(X小于0)或(X == -1)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

变量 X 数据类型为int可能的值: -1,0,1,2,3
其中前pression将以更快的速度(以CPU蜱):

Variable x is int with possible values: -1, 0, 1, 2, 3. Which expression will be faster (in CPU ticks):

1. (x < 0)
2. (x == -1)

语言:C / C ++,但我想其他语言将具有相同

Language: C/C++, but I suppose all other languages will have the same.

P.S。我个人认为,答案是(X小于0)。

P.S. I personally think that answer is (x < 0).

更广泛的大师:如果 X 1 2 ^ 30

More widely for gurus: what if x from -1 to 2^30?

推荐答案

这完全取决于你编译的ISA和编译器的优化质量。不要优化prematurely:个人资料首先要找到你的瓶颈

That depends entirely on the ISA you're compiling for, and the quality of your compiler's optimizer. Don't optimize prematurely: profile first to find your bottlenecks.

这就是说,在x86上,你会发现两者都是一样快在大多数情况下。在这两种情况下,你就会有一个比较( CMP )和一个条件跳转(江铜)的说明。然而,对于(X小于0),可能有某些情况下,编译器可以的Elid的 CMP 指令,通过加快你的code的一整周

That said, in x86, you'll find that both are equally fast in most cases. In both cases, you'll have a comparison (cmp) and a conditional jump (jCC) instructions. However, for (x < 0), there may be some instances where the compiler can elide the cmp instruction, speeding up your code by one whole cycle.

特别是,如果该值 X 被存储在寄存器中并且是最近(如的算术运算的结果添加,但还有更多的可能性),设置符号标志SF在EFLAGS寄存器中,那么就没有必要在 CMP 指令,编译器可以发射只是一个 JS 指令。有没有简单的跳转当输入为-1 JCC 指令。

Specifically, if the value x is stored in a register and was recently the result of an arithmetic operation (such as add, or sub, but there are many more possibilities) that sets the sign flag SF in the EFLAGS register, then there's no need for the cmp instruction, and the compiler can emit just a js instruction. There's no simple jCC instruction that jumps when the input was -1.

这篇关于这是更快的(X小于0)或(X == -1)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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