我需要将一个大的 csv 文件写入磁盘。我已将问题简化为以下代码。当我使用 VS 2017 在我的 Windows 7 机器上运行编译时,它平均运行 26 秒。有人可以建议一种在不更改数据容器或输出格式的情况下加快速度的方法吗?任何帮助将不胜感激。
PS:可能很明显,但加速应该是针对硬件的基本情况
我尝试使用 fopen 和 fprintf,但结果更糟。我也试过设置缓冲区大小但没有成功。
#include <iostream>
#include <iomanip>
#include <fstream>
#include <chrono>
#include <vector>
#include <string>
typedef std::chrono::high_resolution_clock Clock;
typedef std::vector<double> VecD;
typedef std::vector<VecD> VecVecD;
void test_file_write_stream() {
VecVecD v(10000, VecD(2000, 1.23456789));
const std::string delimiter(",");
const std::string file_path("c:\\junk\\speedtest.csv");
auto t1_stream = Clock::now();
std::ofstream ostream(file_path.c_str());
if (!ostream.good())
return;
ostream << std::setprecision(12);
for (const auto & row : v) {
for (const auto & col : row) {
ostream << col << delimiter;
}
ostream << std::endl;
}
auto t2_stream = Clock::now();
std::cout << "Stream test: " << std::chrono::duration_cast<std::chrono::microseconds>(t2_stream - t1_stream).count() / 1.0e6 << " seconds" << std::endl;
}
void main(int argc, char * argv[]) {
test_file_write_stream();
}
流测试:26.2086 秒
最佳答案
根据wikipedi,您不想使用的是内存映射文件 :
The benefit of memory mapping a file is increasing I/O performance, especially when used on large files.
为什么?因为不需要在额外时间复制数据 - 并且您应该开始看到大概增加了 50%-100% 或更多。
boost在 boost-interprocess 中有一个非常整洁的界面.我没有这个 atm 的测试台,但是有点像:
boost::interprocess::file_mapping fm(filename, ...);
boost::interprocess::mapped_region region(fm, ...);
//mapped_region is a memory mapped file
否则,您当然可以使用适合您平台的界面:
https://learn.microsoft.com/en-us/dotnet/standard/io/memory-mapped-files
关于c++ - 在 C++ 中加速大文件写入磁盘,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58295059/