I'm going to calculate the size of the vector. If I write this code:
Eigen::Matrix<float, 6, 1, Eigen::ColMajor> staticVector;
std::cout << "sizeInBytes: " << sizeof (staticVector) << std::endl;
the output is:
sizeInBytes: 24
But if I write:
Eigen::Matrix<float, Eigen::Dynamic, 1, Eigen::ColMajor> dynamicVector;
dynamicVector.resize(6);
std::cout << "sizeInBytes: " << sizeof (dynamicVector) << std::endl;
the output is:
sizeInBytes: 16
Okay, the sizeof (vector) doesn't show the real size of the dynamic vector. What should I use? I would try sizeof (float) * vector.size() or sizeof (float) * vector.size() + sizeof (vector), but not sure if this is the correct option. So what do I need?
If Eigen::Matrix
's array is all in the stack, then sizeof
should return the right value. This would be great for small Matrices, but could become dangerous for largest, as it could cause stack overflow.
If data are stored in the heap then you need to make a method that adds stack and heap memory and returns it. This would be an possible example:
template<class T, size_t ROWS, size_t COLS, Eigen::SomeEnumType>
class Matrix {
// ...
private:
std::array<std::array<T, COLS>, ROWS> *data;
public:
Matrix() { data = new std::array<std::array<T, COLS>, ROWS>(); }
// Assumes all dynamically allocated memory is the data.
size_t sizeInBytes() const { return sizeof(T) * ROWS * COLS + sizeof(*this); }
};
About the concern in the comment:
I am trying to transfer a dynamic vector to the GPU using Cuda
I've worked very little with CUDA so I might be wrong, but IIRC the only way to put things to the GPU with with a memcpy
-like operation. This would be very hard to impossible for vectors, which contain both stack and heap data far from each other. The best way would be to allocate all data inside the object (so it's contiguous in memory), and then if you're scared of stack overflow simply allocate the whole object on the heap:
template<class T, size_t ROWS, size_t COLS, Eigen::SomeEnumType>
class Matrix {
// ...
std::array<std::array<T, COLS>, ROWS> data;
};
int main() {
auto *mat = new Eigen::Matrix<float, 6, 1, Eigen::ColMajor>(...);
void *GPU_mat = malloc_GPU(sizeof(*mat));
memcpy_to_GPU(GPU_mat, mat, sizeof(*mat));
}