我需要在下一次中断命中之前使用缓冲区中的数据并复制到一个大的保存数组中。循环复制不是一种选择。太慢了。在完成所有复制之前,我不需要组合数据的多维结构,这意味着我可以将Buffer.BlockCopy() 复制到一维数组,然后再次复制到多维数组以获得所需的结构。下面是一些代码(在控制台中运行),将展示该技术以及性能。
static class Program
{
[STAThread]
static void Main()
{
Stopwatch watch = new Stopwatch();
const int width = 2;
const int depth = 10 * 1000000;
// Create a large array of data
Random r = new Random(100);
int[,] data = new int[width, depth];
for(int i = 0; i < width; i++)
{
for(int j = 0; j < depth; j++)
{
data[i, j] = r.Next();
}
}
// Block copy to a single dimension array
watch.Start();
int[] buffer = new int[width * depth];
Buffer.BlockCopy(data, 0, buffer, 0, data.Length * sizeof(int));
watch.Stop();
Console.WriteLine("BlockCopy to flat array took {0}", watch.ElapsedMilliseconds);
// Block copy to multidimensional array
int[,] data2 = new int[width, depth];
watch.Start();
Buffer.BlockCopy(buffer, 0, data2, 0,buffer.Length * sizeof(int));
watch.Stop();
Console.WriteLine("BlockCopy to 2 dimensional array took {0}", watch.ElapsedMilliseconds);
// Now try a loop based copy - eck!
data2 = new int[width, depth];
watch.Start();
for (int i = 0; i < width; i++)
{
for (int j = 0; j < depth; j++)
{
data2[i, j] = data[i, j];
}
}
watch.Stop();
Console.WriteLine("Loop-copy to 2 dimensional array took {0} ms", watch.ElapsedMilliseconds);
}
}
输出:
BlockCopy to flat array took 14 ms
BlockCopy to 2 dimensional array took 28 ms
Loop-copy to 2 dimensional array took 149 ms