Sha*_*mer 8 .net c# arrays clr
似乎C#在添加两个数组时UInt16[]比在添加两个数组时更快int[].这对我来说没有意义,因为我会假设数组是字对齐的,因此int[]需要较少的CPU工作,不是吗?
我运行下面的测试代码,得到以下结果:
Int for 1000 took 9896625613 tick (4227 msec)
UInt16 for 1000 took 6297688551 tick (2689 msec)
Run Code Online (Sandbox Code Playgroud)
测试代码执行以下操作:
aand的数组b,一次.a和b逐项添加.这样做了1000次.这是为了int[] a, b和为UInt16 a,b.而每次我运行的代码时,为测试UInt16阵列需要30%不到的时间-50%int阵列.你能解释一下吗?
这是代码,如果你想尝试自己:
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)");
}
Run Code Online (Sandbox Code Playgroud)
会发生什么是你看到漏洞的抽象.UInt16占用int的一半内存(16对32位).
这意味着int16数组占用的内存区域占用int32所占区域的一半.因此,更多的区域可以适应处理器缓存,因此可以非常快速地访问.
您可以在具有更多缓存的处理器上尝试该代码,并且差异可能更小.
也尝试使用更大的阵列.
| 归档时间: |
|
| 查看次数: |
1105 次 |
| 最近记录: |