// ================================================================== // Author: Jean-Michel RICHER // Email: jean-michel.richer@univ-angers.fr // Institution: LERIA, Faculty of Science // University of Angers, France // ================================================================== #include #include #include #include using namespace std; /* ================================================================== * SUBPROGRAM * * void share_elements(int N, int K, vector& velems); * * WHAT * * Distribute @param(N) elements over @param(K) processors * * HOW * * Assume that the number of elements is well distributed over * the processors * * PARAMETERS * * @paramdef(int, N) : number of elements * @paramdef(int, K) : number of processors / process / threads * @paramdef(vector&, velems) : vector that receives for each * processor the number of elements it will have to treat * * ================================================================== */ void share_elements(int N, int K, vector& velems) { int u_2 = N / K, left = N; int k; for (k = 0; k < K; ++k) { velems.push_back( u_2 ); left -= u_2; } k = 0; while (left != 0) { ++velems[ k ]; --left; // here the '% K' is not necessary has there are left < K // elements to place k = (k + 1 ) % K; } } /* ================================================================== * SUBPROGRAM * * int main(int argc, char *argv[]) * * WHAT * * Main program * * PARAMETERS * * @paramdef(int,argc) : number of command line arguments * @paramdef(char **, argv) : command line arguments as C-strings * * ================================================================== */ int main(int argc, char *argv[]) { // Number of elements, i.e. size of an array int N = 105; // Number of processors / process / threads int K = 6; if (argc > 1) N = atoi( argv[1] ); if (argc > 2) K = atoi( argv[2] ); vector v_nbr_elements; share_elements( N, K, v_nbr_elements ); cout << "-------------------" << endl; for (int k = 0; k < K; ++k) { cout << "k=" << k << ", #elements=" << v_nbr_elements[ k ] << endl; } int sum = accumulate( v_nbr_elements.begin(), v_nbr_elements.end(), 0); cout << "-------------------" << endl; cout << "sum=" << sum << endl; cout << "-------------------" << endl; return EXIT_SUCCESS; }