签名VS用C无符号运算 [英] Signed vs Unsigned operations in C

查看:159
本文介绍了签名VS用C无符号运算的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单的问题:

我有一个程序做很多很多了整数和长期多头数学计算。为了适应一个额外的位,我做了长期多头未签名,因为我只处理了正数,现在可以得到一些更多的值。

I have a program doing lots and lots of mathematical computations over ints and long longs. To fit in an extra bit, I made the long longs unsigned, since I only dealt with positive numbers, and could now get a few more values.

奇怪的是,这给了我15%的性能提升,我确认在简单地使所有的很长很长的无符号的。

Oddly enough, this gave me a 15% performance boost, which I confirmed to be in simply making all the long long's unsigned.

这可能吗?是数学运算与无符号数真的快?我记得读这不会有什么区别,编译器会自动挑选出去无论签名与否的最快方法。这是15%的提升真正从制作瓦尔无符号,或可以是别的东西影响了我的code?

Is this possible? Are mathematical operations really faster with unsigned numbers? I remember reading that there would be no difference, and the compiler automatically picks out the fastest way to go whether signed or unsigned. Is this 15% boost really from making the vars unsigned, or could it be something else affected in my code?

和,如果真的是自作出瓦尔无符号,应我的目标是让一切(甚至整数)符号,因为我从来不需要负数,并且每一秒都是重要的,如果我能救它。

And, if it really is from making the vars unsigned, should I aim to make everything (even ints) unsigned, as I never need negative numbers, and every second is important if I can save it.

推荐答案

在某些操作,符号的整数更快,在别人未签名的速度更快:

In some operations, signed integers are faster, in others, unsigned are faster:


  • 在C,可以假定符号整数运算不换行。编译器将利用这循环优化,例如。比较同样可以优化掉。 (这也可能会导致微妙的错误,如果你不希望这样)。

  • In C, signed integer operations can be assumed not to wrap. The compiler will take advantage of this in loop optimization, for example. Comparisons can be optimized away similarly. (This can also lead to subtle bugs if you don't expect this).

在另一方面,无符号整数没有这个假设。但是,没有处理的标志是一个很大的优势,对一些操作,例如:分工。通过两个恒功率的无符号除法是一个简单的转变,但(这取决于您的四舍五入规则)有一个有条件的off-by-1为负数。

On the other hand, unsigned integers do not have this assumption. However, not having to deal with a sign is a big advantage for some operations, for example: division. Unsigned division by a constant power of two is a simple shift, but (depending on your rounding rules) there's a conditional off-by-1 for negative numbers.

就个人而言,我只作使用无符号整数,除非我真的,真的有这需要签署一个价值的习惯。这与其说是对性能的正确性。

Personally, I make a habit of only using unsigned integers unless I really, really do have a value which needs to be signed. It's not so much for performance as correctness.

您可能会看到长长的,这(我猜)是在您的案件64位放大的效果。该CPU通常没有一条指令做处理这些类型(在32位模式),因此签署业务略有增加的复杂性将更加明显。

You may see the effect magnified with long long, which (I'm guessing) is 64 bits in your case. The CPU usually doesn't have single instructions do deal with these types (in 32 bit mode), so the slight added complexity for signed operations will be more noticeable.

这篇关于签名VS用C无符号运算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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