Eigen 库中 UnaryExpr 对矩阵元素施加函数的性能比较

测试使用的头函数

#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秒。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值