我正试图将大量的数据写入我的SSD(固态硬盘)。我说的巨大是指80GB。

我在网上寻找解决方案,但我想到的最好的办法是:

#include <fstream>
const unsigned long long size = 64ULL*1024ULL*1024ULL;
unsigned long long a[size];
int main()
{
    std::fstream myfile;
    myfile = std::fstream("file.binary", std::ios::out | std::ios::binary);
    //Here would be some error handling
    for(int i = 0; i < 32; ++i){
        //Some calculations to fill a[]
        myfile.write((char*)&a,size*sizeof(unsigned long long));
    }
    myfile.close();
}

使用Visual Studio 2010编译,完全优化,在Windows7下运行,该程序最大可达20MB/s左右。真正困扰我的是,Windows可以以150MB/s到200MB/s之间的速度将文件从另一个SSD复制到这个SSD。至少快7倍。这就是为什么我认为我应该能跑得更快。

有什么办法可以加快我的写作速度吗?


当前回答

尝试使用内存映射文件。

其他回答

如果你在资源管理器中将一些东西从磁盘A复制到磁盘B, Windows使用DMA。这意味着对于大多数的复制过程,CPU基本上什么也不做,只是告诉磁盘控制器在哪里放置数据,并从哪里获取数据,从而消除了整个链中的一个步骤,而且这个步骤根本不适合移动大量数据(我指的是硬件)。

你所做的事情涉及到CPU很多。 我想给你指出“一些计算来填充[]”部分。我认为这是必要的。你生成一个[],然后你从一个[]复制到一个输出缓冲区(这就是fstream::write所做的),然后你再次生成,等等。

怎么办呢?多线程!(我希望你有一个多核处理器)

叉。 使用一个线程生成一个[]数据 使用另一个将a[]中的数据写入磁盘 您将需要两个数组a1[]和a2[],并在它们之间进行切换 您将需要在线程(信号量、消息队列等)之间进行某种同步。 使用较低级别的、无缓冲的函数,比如Mehrdad提到的WriteFile函数

按顺序尝试以下方法:

Smaller buffer size. Writing ~2 MiB at a time might be a good start. On my last laptop, ~512 KiB was the sweet spot, but I haven't tested on my SSD yet. Note: I've noticed that very large buffers tend to decrease performance. I've noticed speed losses with using 16-MiB buffers instead of 512-KiB buffers before. Use _open (or _topen if you want to be Windows-correct) to open the file, then use _write. This will probably avoid a lot of buffering, but it's not certain to. Using Windows-specific functions like CreateFile and WriteFile. That will avoid any buffering in the standard library.

fstreams本身并不比C流慢,但是它们使用更多的CPU(特别是在没有正确配置缓冲的情况下)。当CPU饱和时,会限制I/O速率。

至少MSVC 2015实现在没有设置流缓冲区时一次复制1个字符到输出缓冲区(参见streambuf::xsputn)。所以一定要设置一个流缓冲区(>0)。

使用以下代码,我可以用fstream获得1500MB/s的写入速度(我的M.2 SSD的全速):

#include <iostream>
#include <fstream>
#include <chrono>
#include <memory>
#include <stdio.h>
#ifdef __linux__
#include <unistd.h>
#endif
using namespace std;
using namespace std::chrono;
const size_t sz = 512 * 1024 * 1024;
const int numiter = 20;
const size_t bufsize = 1024 * 1024;
int main(int argc, char**argv)
{
  unique_ptr<char[]> data(new char[sz]);
  unique_ptr<char[]> buf(new char[bufsize]);
  for (size_t p = 0; p < sz; p += 16) {
    memcpy(&data[p], "BINARY.DATA.....", 16);
  }
  unlink("file.binary");
  int64_t total = 0;
  if (argc < 2 || strcmp(argv[1], "fopen") != 0) {
    cout << "fstream mode\n";
    ofstream myfile("file.binary", ios::out | ios::binary);
    if (!myfile) {
      cerr << "open failed\n"; return 1;
    }
    myfile.rdbuf()->pubsetbuf(buf.get(), bufsize); // IMPORTANT
    for (int i = 0; i < numiter; ++i) {
      auto tm1 = high_resolution_clock::now();
      myfile.write(data.get(), sz);
      if (!myfile)
        cerr << "write failed\n";
      auto tm = (duration_cast<milliseconds>(high_resolution_clock::now() - tm1).count());
      cout << tm << " ms\n";
      total += tm;
    }
    myfile.close();
  }
  else {
    cout << "fopen mode\n";
    FILE* pFile = fopen("file.binary", "wb");
    if (!pFile) {
      cerr << "open failed\n"; return 1;
    }
    setvbuf(pFile, buf.get(), _IOFBF, bufsize); // NOT important
    auto tm1 = high_resolution_clock::now();
    for (int i = 0; i < numiter; ++i) {
      auto tm1 = high_resolution_clock::now();
      if (fwrite(data.get(), sz, 1, pFile) != 1)
        cerr << "write failed\n";
      auto tm = (duration_cast<milliseconds>(high_resolution_clock::now() - tm1).count());
      cout << tm << " ms\n";
      total += tm;
    }
    fclose(pFile);
    auto tm2 = high_resolution_clock::now();
  }
  cout << "Total: " << total << " ms, " << (sz*numiter * 1000 / (1024.0 * 1024 * total)) << " MB/s\n";
}

我在其他平台(Ubuntu, FreeBSD)上尝试了这段代码,没有注意到I/O率的差异,但CPU使用率的差异约为8:1 (fstream使用了8倍多的CPU)。所以可以想象,如果我有一个更快的磁盘,fstream写速度会比stdio版本慢。

尝试使用open()/write()/close() API调用并试验输出缓冲区的大小。我的意思是不要一次传递整个“多-多-字节”缓冲区,做几次写入(即TotalNumBytes / OutBufferSize)。OutBufferSize可以从4096字节到兆字节。

另一个尝试——使用WinAPI OpenFile/CreateFile并使用这篇MSDN文章来关闭缓冲(FILE_FLAG_NO_BUFFERING)。这篇关于WriteFile()的MSDN文章展示了如何获取驱动器的块大小以了解最佳缓冲区大小。

不管怎样,std::ofstream是一个包装器,可能会阻塞I/O操作。请记住,遍历整个n gb数组也需要一些时间。当您写入一个小缓冲区时,它会更快地到达缓存并工作。

我发现std::stream/FILE/device之间没有区别。 在缓冲和非缓冲之间。

还要注意:

SSD驱动器“倾向于”变慢(更低的传输速率),因为它们被填满了。 SSD驱动器“倾向于”变慢(更低的传输速率),因为它们变老了(因为没有工作位)。

我看到代码在63秒内运行。 因此传输速率为:260M/s(我的SSD看起来比你的快一点)。

64 * 1024 * 1024 * 8 /*sizeof(unsigned long long) */ * 32 /*Chunks*/

= 16G
= 16G/63 = 260M/s

我从std::fstream移动到FILE*没有增加。

#include <stdio.h>

using namespace std;

int main()
{
    
    FILE* stream = fopen("binary", "w");

    for(int loop=0;loop < 32;++loop)
    {
         fwrite(a, sizeof(unsigned long long), size, stream);
    }
    fclose(stream);

}

因此,c++流的工作速度与底层库所允许的一样快。

但我认为将操作系统与构建在操作系统之上的应用程序进行比较是不公平的。应用程序不能做任何假设(它不知道驱动器是SSD),因此使用操作系统的文件机制进行传输。

而操作系统不需要做任何假设。它可以告诉所涉及的驱动器的类型,并使用最佳的技术来传输数据。在这种情况下,是直接内存到内存的传输。试着写一个程序,把80G从内存的一个位置复制到另一个位置,看看有多快。

Edit

我修改了我的代码,以使用较低级别的调用: 没有缓冲。

#include <fcntl.h>
#include <unistd.h>


const unsigned long long size = 64ULL*1024ULL*1024ULL;
unsigned long long a[size];
int main()
{
    int data = open("test", O_WRONLY | O_CREAT, 0777);
    for(int loop = 0; loop < 32; ++loop)
    {   
        write(data, a, size * sizeof(unsigned long long));
    }   
    close(data);
}

这没什么区别。

注意:我的驱动器是SSD驱动器,如果你有一个普通的驱动器,你可能会看到上面两种技术之间的区别。但正如我所期望的那样,非缓冲和缓冲(当写入大于缓冲区大小的大块时)没有区别。

编辑2:

你试过用c++复制文件的最快方法吗

int main()
{
    std::ifstream  input("input");
    std::ofstream  output("ouptut");

    output << input.rdbuf();
}