Skip to content

Instantly share code, notes, and snippets.

@valmat
Created January 16, 2022 17:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save valmat/a35b42932c0f71664f55d756112ab3a6 to your computer and use it in GitHub Desktop.
Save valmat/a35b42932c0f71664f55d756112ab3a6 to your computer and use it in GitHub Desktop.
Evenly splits the values range for load balancing CPU cores
#include <iostream>
#include <utility>
#include <vector>
// Равномерно разделяет диапазон значения
// Для балансировки нагрузки на ядра CPU
std::vector<std::pair<int, int>>
splitRange(int from, int to, uint threads) noexcept
{
std::vector<std::pair<int, int>> pairs;
pairs.reserve(threads);
std::cerr << "from : " << from << std::endl;
std::cerr << "to : " << to << std::endl;
std::cerr << "threads: " << threads << std::endl;
int range_len = to - from + 1;
int sub_len = range_len / threads;
uint rest_len = range_len % threads;
std::cerr << "range_len : " << range_len << std::endl;
std::cerr << "sub_len : " << sub_len << std::endl;
std::cerr << "rest_len : " << rest_len << std::endl;
std::cerr << "******** : " << (sub_len * threads + rest_len) << std::endl;
int cur_from = from;
int cur_to;
for (uint i = 0; i < rest_len && cur_from <= to; ++i) {
cur_to = cur_from + sub_len;
std::cerr << "(" << cur_from << ", " << cur_to << ")+[" << (cur_to - cur_from + 1) << "]" << std::endl;
pairs.emplace_back(cur_from, cur_to);
cur_from = cur_to + 1;
}
for (uint i = rest_len; i < threads && cur_from <= to; ++i) {
cur_to = cur_from + sub_len - 1 ;
std::cerr << "(" << cur_from << ", " << cur_to << ")*[" << (cur_to - cur_from + 1) << "]" << std::endl;
pairs.emplace_back(cur_from, cur_to);
cur_from = cur_to + 1;
}
return pairs;
}
int main()
{
int a = -45, b = 45;
uint threads = 8;
splitRange(a, b, threads);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment