void ThinkOne::test_multi_file_release_source()
{
try
{
const size_t fileCount = 256;
const size_t totalFileBytes = 1024ull * 1024ull * 1024ull * 16ull;
const size_t fileBytes = totalFileBytes / fileCount;
HORSE_DEBUG("fileBytes:%llu M", fileBytes / (1024ull * 1024ull));
std::vector<std::string> fileNameList;
for (size_t i = 0; i < fileCount; ++i)
{
char szBuf[1024] = { 0 };
_snprintf_s(szBuf, 1024, "d:/files/h_%d.txt", (int)i);
fileNameList.push_back(szBuf);
}
HORSE_DEBUG("createFile begin");
for (int i = 0; i < fileNameList.size(); ++i)
{
if (!createFile(fileNameList[i], fileBytes))
{
HORSE_ERROR("createFile failed!");
return;
}
}
HORSE_DEBUG("createFile end");
const size_t bytesPerBlock = 1024 * 64;
const size_t totalCount = fileBytes / bytesPerBlock;
HORSE_DEBUG("totalCount:%llu", totalCount);
HORSE_DEBUG("[%s] test ********************", __FUNCTION__);
std::vector<uint8_t> buf;
buf.resize(bytesPerBlock + 1); // note: resize
for (const auto& fileName : fileNameList)
{
file_mapping fileMapping(fileName.c_str(), read_write);
HORSE_DEBUG("memset begin:[%llu,%llu) - %s", 0, totalCount, fileMapping.get_name());
size_t offset = 0;
uint8_t* addr = nullptr;
for (size_t i = 0; i < totalCount; ++i)
{
offset = i * bytesPerBlock;
mapped_region mappedRegion(fileMapping, read_write, offset, bytesPerBlock);
addr = (uint8_t*)mappedRegion.get_address();
//write
memset(addr, 98, bytesPerBlock);
//read
//memcpy_s(buf.data(), buf.size(), addr, bytesPerBlock);
//if (buf[bytesPerBlock - 1] != 98)
//{
// throw 5;
//}
//mappedRegion.flush();
}
HORSE_DEBUG("memset end:[%llu,%llu) - %s", 0, totalCount, fileMapping.get_name());
}
HORSE_DEBUG("[%s] end", __FUNCTION__);
}
catch (interprocess_exception& e)
{
cout << e.what() << endl;
assert(!"throw interprocess_exception!");
}
return;
}
上述代码:
1.测试环境:Win10系统,16G内存
2.映射256个文件,总大小为16G
3.及时释放句柄
发现:
下面所有情况,进程的内存使用都很小
1.如果只进行"读"的动作 ,内存占比很小 (资源监视器中:物理内存"已修改"基本为0)
//read
memcpy_s(buf.data(), buf.size(), addr, bytesPerBlock);
耗时: 0:21
2.如果只进行"写"的动作
(1)如果不及时保存到磁盘上,也就是不调用 mappedRegion.flush(),此种情况内存占比很大
(资源监视器中:物理内存"已修改"基本爆满)
耗时: 0:21
(2)如果调用 mappedRegion.flush(),此种情况内存占比很小
(资源监视器中:物理内存"已修改"大约在190M)
耗时: 1:37