我创建了一个"boost::interprocess::managed_shared_memory“实例,并使用"2 * 1024 * 1024 * 1024”元素构造了一个char数组。不幸的是,这花费了超过50秒的时间。
namespace bip = boost::interprocess;
auto id_ = "shmTest"s;
size_t size_ = 2*1024*1024*1024ul;
auto ashmObj_ = make_unique<bip::managed_shared_memory>(bip::create_only,
id_.c_str(),
size_ );
auto data_ = shmObj_->construct<char>("Data")[size_]('\0');
在那之后,我摆脱了它的初始化,把时间缩短到30秒。
auto data_ = shmObj_->construct<char>("Data")[size_]();
有什么办法让这次行动的时机更好吗?
发布于 2022-11-29 11:57:36
Sidenote:我不认为大小计算表达式是安全的,因为你似乎认为(ul):https://cppinsights.io/s/c34003a4
给出的代码在bad_alloc
中总是失败的,因为您没有考虑到段管理器的开销:
修复它,就像这样运行在5s为我:
#include <boost/interprocess/managed_shared_memory.hpp>
namespace bip = boost::interprocess;
int main() {
auto id_ = "shmTest";
size_t size_ = 2ul << 30;
bip::shared_memory_object::remove(id_);
bip::managed_shared_memory sm(bip::create_only, id_, size_ + 1024);
auto data_ = sm.construct<char>("Data")[size_]('\0');
}
变到
auto data_ = sm.construct<char>("Data")[size_]();
没有明显的区别:
如果您想要不透明的char数组,只需直接使用映射的区域:
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
namespace bip = boost::interprocess;
int main() {
auto id_ = "shmTest";
size_t size_ = 2ul << 30;
bip::shared_memory_object::remove(id_);
bip::shared_memory_object sm(bip::create_only, id_, bip::mode_t::read_write);
sm.truncate(size_);
bip::mapped_region mr(sm, bip::mode_t::read_write);
auto data_ = static_cast<char*>(mr.get_address());
}
现在它要快得多:
奖金
如果坚持使用,则可以从段中进行原始分配:
auto data_ = sm.allocate_aligned(size_, 32);
或者,您可以按照它的意图使用该段,让我们来管理您的分配:
#include <boost/interprocess/managed_shared_memory.hpp>
#include <boost/interprocess/containers/vector.hpp>
#include <boost/interprocess/allocators/allocator.hpp>
namespace bip = boost::interprocess;
using Seg = bip::managed_shared_memory;
template <typename T> using Alloc = bip::allocator<T, Seg::segment_manager>;
template <typename T> using Vec = bip::vector<T, Alloc<T>>;
int main() {
auto id_ = "shmTest";
size_t size_ = 2ul << 30;
bip::shared_memory_object::remove(id_);
bip::managed_shared_memory sm(bip::create_only, id_, size_ + 1024);
Vec<char>& vec_ = *sm.find_or_construct<Vec<char>>("Data")(size_, sm.get_segment_manager());
auto data_ = vec_.data();
}
这需要更多的时间:
但这样你就有了很大的灵活性。只需搜索我现有的文章中使用托管共享内存中复杂数据结构的示例:转接器
https://stackoverflow.com/questions/74609901
复制相似问题