Vectorizing An Expression Using Eigen
-
07-02-2021 - |
Question
In my program -- which uses the Eigen library -- I need to operate on 2D vectors. In my inner loop I have the following function:
static inline double eval(double x, double y, double xi, double yi)
{
const double invlen2 = 1/(x*x + y*y);
const double invlen4 = invlen2*invlen2;
const double invlen6 = invlen4*invlen2;
const double x2 = x*x, y2 = y*y;
const double x3 = x2*x, y3 = y2*y;
const double xi2 = xi*xi, yi2 = yi*yi;
return x*invlen2 + invlen4*(x2*xi + 2*x*y*yi - xi*y2)
+ invlen6*(x3*xi2 + 3*x*y2*yi2 + 6*x2*y*xi*yi - 3*x*xi2*y2 - 2*y3*xi*yi - x3*yi2);
}
void f(Vector2d& out, const Vector2d& R, const Vector2d& r)
{
out.x() = eval(R.x(), R.y(), r.x(), r.y());
out.y() = eval(R.y(), R.x(), r.y(), r.x());
}
This expression, although messy, seems like a prime candidate for vectorisation as both the x()
and y()
computations follow identical paths. My question is how to do it with Eigen without needing to manually drop down to assembly.
Solution
This answer has nothing to do with Eigen, but since you mentioned manually dropping down to assembly, I'll add this.
You don't need to use assembly to vectorize code. There are compiler intrinsics that will let manually vectorize without assembly:
That said: It looks like Eigen already has internal support for vectorization, but it doesn't appear to be applicable in your example. So I can see why you want to do it manually.