测试使用的头函数
#include <chrono>
#include <iostream>
#include <Eigen/Dense>
硬极限函数的一般实现
/* 对称硬极限函数
* return value : 1 if m[] > 0.0f
* -1 else
*/
Eigen::MatrixXf hardlims_slow(Eigen::MatrixXf m)
{
Eigen::MatrixXf t(m.rows(), m.cols());
for (int x = 0; x < m.rows(); x++) {
for (int y = 0; y < m.cols(); y++) {
t(x, y) = (m(x, y) > 0.0f) ? 1.0f : -1.0f;
}
}
return t;
}
硬极限函数的UnaryExpr实现
Eigen::MatrixXf hardlims(Eigen::MatrixXf m)
{
return m.unaryExpr([](double x) { return 2.0f*(x >= 0.0f) - 1.0f; });
}
以下是测试代码段
auto t1 = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
for (int i = 0; i < 1000000; i++)
{
m4f_hardlim = hardlims_slow(m4f);
}
auto t2 = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock

这篇博客探讨了两种实现硬极限函数的方法,一种是常规的for循环实现,另一种是利用Eigen库的UnaryExpr进行优化。通过百万次运行的测试,展示了UnaryExpr在性能上的优势,运行时间从约25秒缩短到约10.4秒。这表明使用Eigen库的表达式模板可以显著提高代码效率。
最低0.47元/天 解锁文章
3004

被折叠的 条评论
为什么被折叠?



