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

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

相关推荐
阿珊和她的猫3 小时前
v-scale-scree: 根据屏幕尺寸缩放内容
开发语言·前端·javascript
fouryears_234175 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~6 小时前
C#---StopWatch类
开发语言·c#
lifallen7 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研7 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
快乐的划水a7 小时前
组合模式及优化
c++·设计模式·组合模式
cui__OaO8 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习
星星火柴9368 小时前
关于“双指针法“的总结
数据结构·c++·笔记·学习·算法
鱼鱼说测试9 小时前
Jenkins+Python自动化持续集成详细教程
开发语言·servlet·php
艾莉丝努力练剑9 小时前
【洛谷刷题】用C语言和C++做一些入门题,练习洛谷IDE模式:分支机构(一)
c语言·开发语言·数据结构·c++·学习·算法