测试使用的头函数
#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::now().time_since_epoch()).count();
auto d1 = t2-t1;
std::cout << "duration 1 : " << d1 << std::endl;
for (int i = 0; i < 1000000; i++)
{
m4f_hardlim = hardlims(m4f);
}
auto t3 = std::chrono::duration_cast<std::chrono::microseconds>(std::chrono::system_clock::now().time_since_epoch()).count();
auto d2 = t3 - t2;
std::cout << "duration 2 : " << d2 << std::endl;
测试结果如下
duration 1 : 24998521
duration 2 : 10431488
一般实现百万次运行耗时约25秒,UnaryExpr实现耗时约10.4秒。