swapview-rosetta icon indicating copy to clipboard operation
swapview-rosetta copied to clipboard

c++17: need parallel <execution> example

Open Artoria2e5 opened this issue 4 years ago • 1 comments

Many of the loops will have to be rewritten as std::transform, for_each, and reduce lambda operations.


Before we start using the c++17 ts, we can test libstdc++ STL parallelism with -fopenmp -D_GLIBCXX_PARALLEL. Almost no change to the code is needed, but as far as I can see the only improvement would be on sort() which is pointless.


Possible implementation:

#if defined(PARALLEL)
#include <execution>
// Writing the currying thing takes a lot of time:
// http://cpptruths.blogspot.com/2018/12/simple-template-currying.html
#define sort(...) std::sort(std::execution::par_unseq, __VA_ARGS__)
#define transform(...) std::transform(std::execution::par_unseq, __VA_ARGS__)
#define remove_if(...)  std::remove_if(std::execution::par_unseq, __VA_ARGS__)
#else
using std::sort;
using std::transform;
using std::remove_if;
#endif

/* ... */

auto get_swap() -> std::vector<swap_info> {
  std::vector<swap_info> result;
  auto proc = std::filesystem::directory_iterator{"/proc"};
  transform(proc.begin(), proc.end(), result.begin(), [](const auto& entry) {
    if (int pid = std::strtol(entry.path().filename().c_str(), nullptr, 10))
      if (size_t swp = get_swap_for(entry.path() / "smaps"))
        return {pid, swp, get_comm_for(entry.path() / "cmdline")};
    return {0, 0.0, ""};
  });
  result.erase(remove_if(result.begin(), result.end(), [](const auto& maybe_res) {
    return std::get<0>(maybe_res) == 0;
  }));
  sort(result.begin(), result.end(), [](const auto &lhs, const auto &rhs) {
    return std::get<1>(lhs) < std::get<1>(rhs);
  }); 
  return result;
}

Artoria2e5 avatar Sep 25 '19 16:09 Artoria2e5

The macro trick does not work with the requirement from the standard. You should rename the offending names to make it well-defined, or more idiomatically, avoid these macro names at all.

FrankHB avatar Nov 14 '19 10:11 FrankHB