C#中最快的按位运算

Nealon

在C#中,任何特定的按位运算(AND,OR,XOR等)是否快于其他运算?

我问的原因是因为我知道在硬件中,大多数事物都是使用NAND门构建的,因为少数NAND门可以复制任何其他门。这对高级编程语言有什么影响?或在它们之间进行所有抽象层处理,使它们都以相同的速度运行。

我意识到从中获得的任何性能提升都是微不足道的,我只是出于好奇而问。

编辑:请停止尝试解释没有功能上的原因知道这一点。字面上只是出于好奇。

但是,我通过对两个数字执行一些按位运算来生成HashCode。使用尽可能便宜/最快的操作是有意义的。再说一次,不会有什么不同,我只是很好奇。

编辑:我的问题可以归结为:硬件依赖于较低级别的NAND门的事实是否会对较高级别的进程产生影响?这会导致NAND比XOR快吗?

出于好奇,我问有关硬件细节如何影响软件的问题。这对我来说很有趣。

程序FOX

在C#中,任何特定的按位运算(AND,OR,XOR等)是否快于其他运算?

我创建了一个基准:

Random r = new Random();
int a = r.Next();
int b = r.Next();
int c = 0;
Stopwatch sw = new Stopwatch();

sw.Start();
for (int i = 0; i < int.MaxValue; i++)
{
    c += a & b;
}
sw.Stop();
Console.WriteLine("AND operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
c = 0;
// The above is just to make sure that the optimizer does not optimize the loop away,
// as pointed out by johnnycrash in the comments.
sw.Restart();
for (int i = 0; i < int.MaxValue; i++)
{
    c += a | b;
}
sw.Stop();
Console.WriteLine("OR operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
c = 0;
for (int i = 0; i < int.MaxValue; i++)
{
    c += a ^ b;
}
sw.Stop();
Console.WriteLine("XOR operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
c = 0;
for (int i = 0; i < int.MaxValue; i++)
{
    c += ~a;
}
sw.Stop();
Console.WriteLine("NOT operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
c = 0;
for (int i = 0; i < int.MaxValue; i++)
{
    c += a << 1;
}
sw.Stop();
Console.WriteLine("Left shift operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);
c = 0;
for (int i = 0; i < int.MaxValue; i++)
{
    c += a >> 1;
}
sw.Stop();
Console.WriteLine("Right shift operator: {0} ticks", sw.Elapsed.Ticks);
Console.WriteLine("Result: {0}", c);

它输出以下内容:

AND operator: 7979680 ticks
OR operator: 7826806 ticks
XOR operator: 7826806 ticks
NOT operator: 7826806 ticks
Left shift operator: 7826806 ticks
Right shift operator: 7826806 ticks

AND运算符需要更长时间,因为它是第一个循环。例如,如果我切换AND和OR循环,则OR循环会花费更多时间。

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章