c++ 写文件性能比较

cpp 复制代码
#include <iostream>
#include <fstream>
#include <vector>
#include <chrono>
#include <glog/logging.h>
using milli = std::chrono::milliseconds;

int main()
{
    int num = 1000000000;
    int* arr = new int[num];
    std::ofstream outfile("data.bin", std::ios::binary | std::ios::out);
    std::vector<int> tmp;

    if (!outfile.is_open())
    {
        std::cerr << "Failed to open the file." << std::endl;
        // return 1;
    }

    auto start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < num; i++)
    {
        outfile.write(reinterpret_cast<const char *>(&i), sizeof(i));
    }
    auto end = std::chrono::high_resolution_clock::now();
    std::cout << "直接写入文件耗时:"<<(float)std::chrono::duration_cast<milli>(end - start).count()
              << " milliseconds\n";

    start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < num; i++)
    {
        tmp.push_back(i);
    }
    outfile.write(reinterpret_cast<const char *>(tmp.data()), sizeof(int) * tmp.size());
    end = std::chrono::high_resolution_clock::now();
    std::cout << "放入vector再写入文件: "<<(float)std::chrono::duration_cast<milli>(end - start).count()
              << " milliseconds\n";

    start = std::chrono::high_resolution_clock::now();
    for (int i = 0; i < num; i++)
    {
        arr[i] = i;
    }
    outfile.write(reinterpret_cast<const char *>(arr), sizeof(int) * num);
    end = std::chrono::high_resolution_clock::now();
    std::cout << "预设内存块, 赋值写入:"<<(float)std::chrono::duration_cast<milli>(end - start).count()
              << " milliseconds\n";

    outfile.close();
}

编译执行

bash 复制代码
(py37) hq@nuc:~/tmp/hq$ g++ test.cpp -lglog
(py37) hq@nuc:~/tmp/hq$ ./a.out 
直接写入文件耗时:12037 milliseconds
放入vector再写入文件: 11278 milliseconds
预设内存块, 赋值写入:8115 milliseconds

结论:预设内存,一次性写入新能最高

相关推荐
我就是妖怪4 分钟前
Kimi K2.6 智能效果实测与能力全景展示
开发语言
中二痞7 分钟前
下载Python 版本,环境变量变更以及PyCharm更换python版本
开发语言·python·pycharm
故事和你919 分钟前
洛谷-算法2-3-分治与倍增5
开发语言·数据结构·c++·算法·动态规划·图论
SilentSamsara10 分钟前
标准库精讲:collections/itertools/functools/pathlib 实战
开发语言·vscode·python·青少年编程·pycharm
逻辑驱动的ken14 分钟前
Java高频面试考点场景题17
开发语言·jvm·面试·求职招聘·春招
charlie11451419115 分钟前
通用GUI编程技术——图形渲染实战(三十九)——纹理与采样器:从WIC加载到GPU渲染
开发语言·c++·图形渲染·win32
love530love21 分钟前
Python 3.12 解决 MediaPipe “no attribute ‘solutions‘” 终极方案:基于全版本硬核实测的避坑指南
开发语言·人工智能·windows·python·comfyui·mediapipe·solutions
爱码小白21 分钟前
Python 类五大方法 完整版学习笔记
开发语言·python
Fuly102426 分钟前
java面试知识点复习
java·开发语言·面试
郭涤生32 分钟前
std::condition_variable的使用及主要事项
开发语言·c++