Skip to content

Vectorization with loops #628

@FrancoisFayard

Description

@FrancoisFayard

Hi,

I would like to to use xt::xarray as a multidimensional array in my code where some algorithm are written with loops. For instance, here is an algorithm that compute the diameter of a set of points in the plane. The problem I found with xt::xarray is that the data structure does not let the compiler know that on this code point(j, 0) and point(j + 1, 0) are next to each other in memory. It generates suboptimal code. For instance it does not let them compiler vectorize the code.

What is the recommended way to do that with xtensor?

François

const std::size_t n = 10000;
std::vector<std::size_t> shape = {n, 2};
std::vector<std::size_t> stride = {1, n};
xt::xarray<float, xt::layout_type::dynamic> point(shape, stride);
// Fill point

float ans = 0.0f;
for (std::size_t i = 0; i < n; ++i) {
  for (std::size_t j = i + 1; j < n; ++j) {
    const float dx = point(i, 0) - point(j, 0);
    const float dy = point(i, 1) - point(j, 1);
    const float distance = dx * dx + dy * dy;
    if (distance > ans) {
      ans = distance;
    }
  }
}
ans = std::sqrt(ans);

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions