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
结论:预设内存,一次性写入新能最高