[英]How to increase the buffer size used by rdbuf in c++
我正在使用下面的 c++ 代碼將文件(大小約為 1.5-2 gb)從一個位置復制到另一個位置。
#include <fstream>
int main()
{
std::ifstream src("source_path/file.mp4", std::ios::binary);
std::ofstream dst("destination_path/fileCopy.mp4", std::ios::binary);
dst << src.rdbuf();
}
我已從此處獲取此代碼以理智、安全和有效的方式復制文件
此代碼將文件從源復制到目標大約需要 45 秒。 我知道這里rdbuf
必須有一些與之相關的緩沖區大小,實際上我想增加緩沖區大小以獲得更好的性能,我該如何增加緩沖區?
這是我用來將讀取性能提高約 1.8 倍的方法:
// Open file for binary read.
ifstream in_file(file_name, ios::binary | ios::in);
// Proceed if file was successfully opened.
if (in_file.is_open()) {
// Tried buffer size for 16 transfers. Seems a bit slower than 64.
//const size_t bufsize = max(4096, 2 << (int32_t)log2(block_size >> 4));
// Set buffer size for 64 transfers.
const size_t bufsize = max(4096, 2 << (int32_t)log2(block_sizes[0] >> 6));
auto buf = make_unique<char[]>(bufsize);
in_file.rdbuf()->pubsetbuf(buf.get(), bufsize);
// Create block for holding lines.
auto lmemblock = make_unique<char[]>(block_sizes[i]);
// Move file pointer to start of block.
in_file.seekg(offsets[i]);
// Read memblock of data into memory.
in_file.read(lmemblock.get(), block_sizes[i]);
關鍵行是in_file.rdbuf()->pubsetbuf(buf.get(), bufsize);
這增大了默認緩沖區大小,就我而言,這顯着提高了性能。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.