Reputation: 8941
I have a data structure that is an std::vector
of structs, where each struct also contains an std::vector
. I want to calculate in advance an upper limit to the memory needed to represent the entire structure. TO do this, in testing I want to calculate the memory requirements for a finalized structure and compare it to my estimation.
To do this I use the following code:
struct SequenceInfo {
unsigned long num1;
unsigned long num2;
unsigned long vectorLength;
std::vector<unsigned long> values;
};
// A vector of sequence data to represent all data
typedef std::vector<SequenceInfo> SequenceInfoVec;
void foo(SequenceInfoVec& vec)
{
getVec(vec);
std::size_t actualSize = sizeof(SequenceInfoVec);
for (SequenceInfoVec::iterator it1 = vec.begin(); it1 != vec.end(); ++it1)
{
actualSize += sizeof(SequenceInfo) +
sizeof((*it1).values[0]) * (*it1).values.size();
}
cout << "memory size of vec is: " << actualSize << endl;
}
Is this the correct way to calculate the memory requirements of the data structure, (disregarding small OS overhead for memory allocation)?
Upvotes: 2
Views: 295
Reputation: 170084
Yeah, it's pretty correct. But in my opinion it's best to avoid the explicit mention of types (which you already do to an extent), and replace the raw loop with a named algorithm from the standard library.
For C++14 you have std::accumulate
:
void foo(SequenceInfoVec& vec)
{
getVec(vec);
auto actualSize = std::accumulate(begin(vec), end(vec), sizeof(vec),
[](auto prev, auto const& item) {
return prev +
sizeof (item) +
sizeof(item.values[0]) * item.values.size();
}
);
cout << "memory size of vec is: " << actualSize << endl;
}
And since you don't really care about the computation order, for C++ 17 you can even parallelize the computation with std::reduce
:
void foo(SequenceInfoVec& vec)
{
getVec(vec);
auto actualSize = std::reduce(std::execution::par, begin(vec), end(vec), sizeof(vec),
[](auto prev, auto const& item) {
return prev +
sizeof (item) +
sizeof(item.values[0]) * item.values.size();
}
);
cout << "memory size of vec is: " << actualSize << endl;
}
Upvotes: 2