Created
January 16, 2022 17:22
-
-
Save valmat/a35b42932c0f71664f55d756112ab3a6 to your computer and use it in GitHub Desktop.
Evenly splits the values range for load balancing CPU cores
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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