写你想要的最短的方法是
void foo(Eigen::VectorXf& inout, float threshold)
{
inout = (threshold < inout.array().abs()).select(inout, 0.0f);
}
但是,比较和 select 方法都不会被 Eigen (as of now) 向量化。
如果速度很重要,您需要编写一些手动 SIMD 代码,或者编写支持 packet 方法的自定义函子(这使用 Eigen 的内部功能,因此不能保证稳定!):
template<typename Scalar> struct threshold_op {
Scalar threshold;
threshold_op(const Scalar& value) : threshold(value) {}
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Scalar operator() (const Scalar& a) const{
return threshold < std::abs(a) ? a : Scalar(0); }
template<typename Packet>
EIGEN_DEVICE_FUNC EIGEN_STRONG_INLINE const Packet packetOp(const Packet& a) const {
using namespace Eigen::internal;
return pand(pcmp_lt(pset1<Packet>(threshold),pabs(a)), a);
}
};
namespace Eigen { namespace internal {
template<typename Scalar>
struct functor_traits<threshold_op<Scalar> >
{ enum {
Cost = 3*NumTraits<Scalar>::AddCost,
PacketAccess = packet_traits<Scalar>::HasAbs };
};
}}
然后可以将其传递给unaryExpr:
inout = inout.unaryExpr(threshold_op<float>(threshold));
Godbolt-Demo(应该与 SSE/AVX/AVX512/NEON/...一起使用):https://godbolt.org/z/bslATI
实际上可能是您速度变慢的唯一原因是低于正常的数字。在这种情况下,一个简单的
_MM_SET_FLUSH_ZERO_MODE(_MM_FLUSH_ZERO_ON);
应该做的伎俩(cf:Why does changing 0.1f to 0 slow down performance by 10x?)