C#中最快的按位运算

时间:2014-01-29 15:44:07

标签: c# performance bit-manipulation

在C#中,任何特定的按位运算(AND,OR,XOR等)是否比另一个更快?

我问的原因是因为我知道在硬件中,大多数东西是使用NAND门构建的,因为一些NAND门可以复制任何其他门。这是否对高级编程语言有任何影响?或者在它们之间完成所有抽象层,使它们以相同的速度运行。

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

编辑:请停止尝试解释没有功能原因要知道这一点。这实际上只是好奇心。

但是,我通过对两个数字执行一些按位运算来生成HashCode。使用最便宜/最快的操作是有意义的。再一次,它没有任何区别,我只是好奇。

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

我好奇地问及硬件细节如何影响软件。这对我很有意思。

2 个答案:

答案 0 :(得分:7)

  

在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循环需要更多时间。

答案 1 :(得分:5)

CPU是同步逻辑引擎,由时钟驱动。这些低级操作都在一条指令中执行。