BinaryReader在使用读取大文件(1 GB&GT)时,什么是最好的缓冲区的大小?缓冲区、大文件、大小、是最好的

2023-09-02 01:56:45 作者:路过人间

我读的二进制文件,这里是一个示例:

I'm reading binary files and here is a sample:

public static byte[] ReadFully(Stream input)
{
    byte[] buffer = new byte[16*1024];
    int read;
    while ((read = input.Read(buffer, 0, buffer.Length)) > 0)
    {
        ......
    }

}

显然,缓冲区的大小(16 * 1024)在性能上有极大的推动作用。我读过它依赖于I / O技术( SATA ,的 SSD ,的 SCSI 时,等),也哪些文件存在于它的分区的片段大小(我们可以在格式化分区定义)。

Obviously the buffer size (16*1024) has a great role in performance. I've read that it depends on the I/O technology (SATA, SSD, SCSI, etc.) and also the fragment size of the partition which file exists on it (we can define during the formatting the partition).

但这里的问题是: 有没有公式或最佳实践来定义缓冲区的大小?现在,我正在定义一个基于试验和错误。

But here is the question: Is there any formula or best practice to define the buffer size? Right now, I'm defining based on trial-and-error.

编辑: 我已经与不同的缓冲区大小测试了我的服务器上的应用程序,并获得最佳的性能与4095 * 256 * 16(16  MB)! 4096是4秒慢。

I've tested the application on my server with different buffer sizes, and I get the best performance with 4095*256*16 (16 MB)!!! 4096 is 4 seconds slower.

下面是一些较旧的文章,这是非常有用的,但我仍无法得到的原因:

Here are some older posts which are very helpful but I can't still get the reason:

更快(不安全)在BinaryReader在.NET

优化文件缓冲区读取大小?

文件I / O与流 - 最好的内存缓冲区大小 的

How你确定理想的缓冲区大小,使用的FileInputStream什么时候? 的

推荐答案

顺序文件的编程模式和与.NET 性能是一个伟大的文章中的I / O性能的改善。

"Sequential File Programming Patterns and Performance with .NET" is a great article in I/O performance improvement.

在这个 PDF文件的第8页,它表明带宽缓冲区大小比大八个字节,是恒定的。考虑到该文章已被写入2004年和硬盘驱动器的迈拓250GB的7200转SATA硬盘的,其结果应该是最新的I / O技术的不同。

In page 8 of this PDF file, it shows that the bandwidth for buffer size bigger than eight bytes, is constant. Consider that the article has been written in 2004 and the hard disk drive is "Maxtor 250 GB 7200 RPM SATA disk" and the result should be different by latest I/O technologies.

如果您正在寻找最好的表现来看看 pinvoke.net 或PDF文件的9页时,无缓冲文件的性能测量结果示出更好的结果:

If you are looking for the best performance take a look at pinvoke.net or the page 9 of the PDF file, the un-buffered file performance measurements shows better results:

在无缓冲I / O,磁盘数据直接移动之间的   应用程序地址空间和没有任何中间设备   复制。

In un-buffered I/O, the disk data moves directly between the application’s address space and the device without any intermediate copying. 对于单磁盘,使用.NET框架的默认设置 - 他们提供出色的性能为顺序文件访问。 在创建文件时,pre-分配大的顺序文件(使用SetLength()方法)。这通常时相比,碎片文件由约13%提高速度。 在至少就目前而言,磁盘阵列需要无缓冲I / O,以实现最高的性能 - 缓冲I / O可以比无缓冲I / O慢八倍。我们预计这个问题将在以后的.NET Framework版本中解决。 如果你做你自己的缓存,使用大尺寸的要求(64  KB是一个很好的起点)。使用.NET Framework,单个处理器可以读取并使用无缓冲I / O写入磁盘阵列超过800兆字节/秒。