c++ - 在 C++ 中加速大文件写入磁盘

标签 c++ performance io outputstream

我需要将一个大的 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% 或更多。

中有一个非常整洁的界面.我没有这个 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/

相关文章:

c++ - 在 OSX 上使用不带 header 的 sinf()

python - 如何有效地将方形 numpy 数组旋转不同时间 `np.rot90` ?

.net - 管理到非管理开销

c++ - Windows cpp 目标在较高分辨率下变慢

c - 将文本文件中的一行读取到c中的字符数组中

java - 创建一个 Jar 并向其中添加多个流

windows - 恒定的磁盘写入速度

c++ - 关于 C 中的指针

c++ - 模板类型的特征特化

c++ - 当我尝试使用 dll 中的函数时出现问题