Skip to content

Instantly share code, notes, and snippets.

@hirschsn
Created November 13, 2019 09:35
Show Gist options
  • Select an option

  • Save hirschsn/2a0b11e5451994ecd59205573a3ce9f6 to your computer and use it in GitHub Desktop.

Select an option

Save hirschsn/2a0b11e5451994ecd59205573a3ce9f6 to your computer and use it in GitHub Desktop.
Greedy MPI_Dims_create
/**
* This greedy implementation is exactly what OpenMPI does.
*/
#include <array>
#include <vector>
#include <algorithm>
std::vector<int> prime_factors(int n) {
std::vector<int> fs;
for (int p = 2; n > 1; ++p) {
while (n % p == 0) {
fs.push_back(p);
n /= p;
}
}
return fs;
}
std::array<int, 3> dims_create(int n) {
auto fs = prime_factors(n);
std::array<int, 3> dims = {{1, 1, 1}};
// Greedy algorithm
// Need to assign largest values first in order for the greedy algorithm
// to work. No need to sort, the result of prime_factors() is sorted.
std::for_each(std::rbegin(fs), std::rend(fs), [&dims](auto f) {
*std::min_element(std::begin(dims), std::end(dims)) *= f;
});
std::sort(std::rbegin(dims), std::rend(dims));
return dims;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment