如何对齐Eigen矩阵的每一列?

huangapple go评论51阅读模式
英文:

How to align every column of an Eigen matrix?

问题

如果Eigen矩阵的行数不是对齐步长(通常为16字节)的倍数,那么似乎只有矩阵的第一列会对齐。例如:

Eigen::MatrixXf m(7, 7);
std::cout << "1st column start address: " << &m(0, 0) << "\n";
std::cout << "2nd column start address: " << &m(0, 1) << "\n";
1st column start address: 0x100704c80
2nd column start address: 0x100704c9c

第一列对齐,第二列不对齐。

我正在编写外部SIMD代码,用于访问这个矩阵。如果我们能保证每列从一个对齐的地址开始,那么它可能是最快的。有什么惯用的方法可以让Eigen分配我的矩阵,使得每列都是对齐的?

英文:

If the number of rows in an Eigen matrix is not a multiple of the alignment step (usually 16 bytes), then it seems only the first column of the matrix will be aligned. For example:

Eigen::MatrixXf m(7, 7);
std::cout &lt;&lt; &quot;1st column start address: &quot; &lt;&lt; &amp;m(0, 0) &lt;&lt; &quot;\n&quot;;
std::cout &lt;&lt; &quot;2nd column start address: &quot; &lt;&lt; &amp;m(0, 1) &lt;&lt; &quot;\n&quot;;
1st column start address: 0x100704c80
2nd column start address: 0x100704c9c

The first column is aligned, the second is not.

I am writing external SIMD code that accesses this matrix. It can be fastest if we can guarantee that each column starts at an aligned address. What is the idiomatic way to have Eigen allocate my matrix such that every column is aligned?

答案1

得分: 2

以下是要翻译的内容:
这是我现在使用的方法。 这并不理想,因为矩阵的用户必须始终使用topRows()或类似的技巧来使.rows()返回所需数量的活动行。

// 将行数/列数向上取整,以确保每列/行都对齐开始
template <class M>
inline void resizeAligned(M &m, Eigen::Index rows, Eigen::Index cols)
{
    static constexpr auto mask = EIGEN_DEFAULT_ALIGN_BYTES - 1;

    auto &size = m.IsRowMajor ? cols : rows;
    size = (size + mask) & ~mask;

    m.resize(rows, cols);
}
英文:

This is what I'm gong with for now. It's not ideal because the user of the matrix must always use topRows() or equivalent technique for .rows() to return desired number of active rows.

// rounds up the number of rows/cols to ensure each col/row starts aligned
template &lt;class M&gt;
inline void resizeAligned(M &amp;m, Eigen::Index rows, Eigen::Index cols)
{
	static constexpr auto mask = EIGEN_DEFAULT_ALIGN_BYTES - 1;
	
	auto &amp;size = m.IsRowMajor ? cols : rows;
	size = (size + mask) &amp; ~mask;

	m.resize(rows, cols);
}

huangapple
  • 本文由 发表于 2023年5月17日 14:12:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/76269019.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定