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

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

相关推荐
NiNg_1_234几秒前
Vue3 Pinia持久化存储
开发语言·javascript·ecmascript
带带老表学爬虫9 分钟前
java数据类型转换和注释
java·开发语言
qianbo_insist12 分钟前
simple c++ 无锁队列
开发语言·c++
zengy513 分钟前
Effective C++中文版学习记录(三)
数据结构·c++·学习·stl
BigYe程普22 分钟前
我开发了一个出海全栈SaaS工具,还写了一套全栈开发教程
开发语言·前端·chrome·chatgpt·reactjs·个人开发
彭于晏68924 分钟前
Android广播
android·java·开发语言
弱冠少年1 小时前
websockets库使用(基于Python)
开发语言·python·numpy
长天一色1 小时前
C语言日志类库 zlog 使用指南(第五章 配置文件)
c语言·开发语言
MinBadGuy1 小时前
【GeekBand】C++设计模式笔记5_Observer_观察者模式
c++·设计模式
一般清意味……1 小时前
快速上手C语言【上】(非常详细!!!)
c语言·开发语言