“小于/大于"的性能优于“小于/大于或等于" [英] Is performance of "less/greater than than" better than "less/greater than or equal to"

查看:81
本文介绍了“小于/大于"的性能优于“小于/大于或等于"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

小于/大于小于/大于或等于进行比较是否在计算上更高效?

Is it computationally more performant to compare less/greater than over less/greater than or equal to?

直觉上,人们可能会认为小于/大于稍微好一点.

Intuitively one could think that less/greater than is marginally better.

编译器是否可以使用一些技巧使比较看起来相同?

Can a compiler use some trick to make the comparisons seem the same?

编译器可以消除例如小于或等于小于 通过将边界增加 1 但如果边界是活动的",则无法执行此操作.

A compiler could eliminate e.g. less than or equal to with less than by incrementing the bound by one but if the bound is "alive" then this cannot be done.

推荐答案

几乎在每个现代 CPU 上,都有 compare/jumpless 和 compare/jumplessequal 指令花费的时间完全相同,因为它们运行在完全相同的硬件上模包括或不包括等于"位.

On virtually every modern CPU, there are compare/jumpless and compare/jumplessequal instructions that take exactly the same amount of time, because it runs through exactly the same hardware modulo including or not the "equals" bit.

在这种情况下,计算不小于"(以及小于")是一种免费的;对于无符号值,它相当于从 CPU 已经执行的二进制补码减法中进位.计算相等更难:CPU 必须确定减法结果的所有位都为零;对于 64 位 CPU,这是一个天真的 64 位和门,它非常大,因此速度很慢.CPU 设计人员知道这一点,并构建了非常快速的网络来快速、准确地检测到这一点,因此它不是瓶颈.

It is the case that computing the "not less than" (and therefoe "less than") is sort of free; for unsigned values, it is equivalent to carry from a twos's complement subtraction, which the CPUs already do. Computing equal is harder: the CPU has to determine that all bits of the result of the subtraction are zero; for 64 bits CPUs, that's naively a 64 bit and-gate which is pretty big and thus slow. The CPU designers know this, and build very fast networks to detect this quickly, precisely so it isn't a bottleneck.

所以答案是NO",或者说清楚,它们花费的时间相同,并且没有编译器技巧可以改变这一点.

So the answer is "NO", or to be clear, they take the same amount of time, and there are no compiler tricks to change that.

这篇关于“小于/大于"的性能优于“小于/大于或等于"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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