gpt4 book ai didi

c# - 为什么 UInt16 数组的加法速度似乎比 int 数组快?

转载 作者:太空狗 更新时间:2023-10-29 18:26:03 32 4
gpt4 key购买 nike

似乎 C# 添加两个 UInt16[] 数组比添加两个 int[] 数组更快。这对我来说毫无意义,因为我假设数组是字对齐的,因此 int[] 需要 CPU 的工作更少,不是吗?

我运行了下面的测试代码,得到了以下结果:

Int    for 1000 took 9896625613 tick (4227 msec)
UInt16 for 1000 took 6297688551 tick (2689 msec)

测试代码执行以下操作:

  1. 一次创建两个名为ab 的数组。
  2. 用随机数据填充它们一次。
  3. 启动秒表。
  4. 逐项添加ab。这样做了 1000 次。
  5. 停止秒表。
  6. 报告花费了多长时间。

这是为 int[] a, bUInt16 a,b 完成的。 每次我运行代码时,UInt16 数组的测试比int 数组花费的时间少 30%-50%。你能给我解释一下吗?

这是代码,如果你想自己试试:

public static UInt16[] GenerateRandomDataUInt16(int length)
{
UInt16[] noise = new UInt16[length];
Random random = new Random((int)DateTime.Now.Ticks);
for (int i = 0; i < length; ++i)
{
noise[i] = (UInt16)random.Next();
}

return noise;
}

public static int[] GenerateRandomDataInt(int length)
{
int[] noise = new int[length];
Random random = new Random((int)DateTime.Now.Ticks);
for (int i = 0; i < length; ++i)
{
noise[i] = (int)random.Next();
}

return noise;
}

public static int[] AddInt(int[] a, int[] b)
{
int len = a.Length;
int[] result = new int[len];
for (int i = 0; i < len; ++i)
{
result[i] = (int)(a[i] + b[i]);
}
return result;
}

public static UInt16[] AddUInt16(UInt16[] a, UInt16[] b)
{
int len = a.Length;
UInt16[] result = new UInt16[len];
for (int i = 0; i < len; ++i)
{
result[i] = (ushort)(a[i] + b[i]);
}
return result;
}


public static void Main()
{
int count = 1000;
int len = 128 * 6000;

int[] aInt = GenerateRandomDataInt(len);
int[] bInt = GenerateRandomDataInt(len);

Stopwatch s = new Stopwatch();
s.Start();
for (int i=0; i<count; ++i)
{
int[] resultInt = AddInt(aInt, bInt);
}
s.Stop();
Console.WriteLine("Int for " + count
+ " took " + s.ElapsedTicks + " tick ("
+ s.ElapsedMilliseconds + " msec)");

UInt16[] aUInt16 = GenerateRandomDataUInt16(len);
UInt16[] bUInt16 = GenerateRandomDataUInt16(len);

s = new Stopwatch();
s.Start();
for (int i=0; i<count; ++i)
{
UInt16[] resultUInt16 = AddUInt16(aUInt16, bUInt16);
}
s.Stop();
Console.WriteLine("UInt16 for " + count
+ " took " + s.ElapsedTicks + " tick ("
+ s.ElapsedMilliseconds + " msec)");


}

最佳答案

发生的事情是你看到了一个有漏洞的抽象。 UInt16 占用的内存是 int 的一半(16 位与 32 位)。

这意味着int16数组占用的内存区域是int32占用的内存区域的一半。因此,更多的区域可以放入处理器缓存中,因此可以非常快速地访问。

您可以在具有更多高速缓存的处理器上尝试该代码,差异可能会更小。

也可以尝试使用更大的数组。

关于c# - 为什么 UInt16 数组的加法速度似乎比 int 数组快?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2627713/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com