random_shuffle.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533
  1. // -*- C++ -*-
  2. // Copyright (C) 2007-2022 Free Software Foundation, Inc.
  3. //
  4. // This file is part of the GNU ISO C++ Library. This library is free
  5. // software; you can redistribute it and/or modify it under the terms
  6. // of the GNU General Public License as published by the Free Software
  7. // Foundation; either version 3, or (at your option) any later
  8. // version.
  9. // This library is distributed in the hope that it will be useful, but
  10. // WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  12. // General Public License for more details.
  13. // Under Section 7 of GPL version 3, you are granted additional
  14. // permissions described in the GCC Runtime Library Exception, version
  15. // 3.1, as published by the Free Software Foundation.
  16. // You should have received a copy of the GNU General Public License and
  17. // a copy of the GCC Runtime Library Exception along with this program;
  18. // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
  19. // <http://www.gnu.org/licenses/>.
  20. /** @file parallel/random_shuffle.h
  21. * @brief Parallel implementation of std::random_shuffle().
  22. * This file is a GNU parallel extension to the Standard C++ Library.
  23. */
  24. // Written by Johannes Singler.
  25. #ifndef _GLIBCXX_PARALLEL_RANDOM_SHUFFLE_H
  26. #define _GLIBCXX_PARALLEL_RANDOM_SHUFFLE_H 1
  27. #include <limits>
  28. #include <bits/stl_numeric.h>
  29. #include <parallel/parallel.h>
  30. #include <parallel/random_number.h>
  31. namespace __gnu_parallel
  32. {
  33. /** @brief Type to hold the index of a bin.
  34. *
  35. * Since many variables of this type are allocated, it should be
  36. * chosen as small as possible.
  37. */
  38. typedef unsigned short _BinIndex;
  39. /** @brief Data known to every thread participating in
  40. __gnu_parallel::__parallel_random_shuffle(). */
  41. template<typename _RAIter>
  42. struct _DRandomShufflingGlobalData
  43. {
  44. typedef std::iterator_traits<_RAIter> _TraitsType;
  45. typedef typename _TraitsType::value_type _ValueType;
  46. typedef typename _TraitsType::difference_type _DifferenceType;
  47. /** @brief Begin iterator of the __source. */
  48. _RAIter& _M_source;
  49. /** @brief Temporary arrays for each thread. */
  50. _ValueType** _M_temporaries;
  51. /** @brief Two-dimensional array to hold the thread-bin distribution.
  52. *
  53. * Dimensions (_M_num_threads + 1) __x (_M_num_bins + 1). */
  54. _DifferenceType** _M_dist;
  55. /** @brief Start indexes of the threads' __chunks. */
  56. _DifferenceType* _M_starts;
  57. /** @brief Number of the thread that will further process the
  58. corresponding bin. */
  59. _ThreadIndex* _M_bin_proc;
  60. /** @brief Number of bins to distribute to. */
  61. int _M_num_bins;
  62. /** @brief Number of bits needed to address the bins. */
  63. int _M_num_bits;
  64. /** @brief Constructor. */
  65. _DRandomShufflingGlobalData(_RAIter& __source)
  66. : _M_source(__source) { }
  67. };
  68. /** @brief Local data for a thread participating in
  69. __gnu_parallel::__parallel_random_shuffle().
  70. */
  71. template<typename _RAIter, typename _RandomNumberGenerator>
  72. struct _DRSSorterPU
  73. {
  74. /** @brief Number of threads participating in total. */
  75. int _M_num_threads;
  76. /** @brief Begin index for bins taken care of by this thread. */
  77. _BinIndex _M_bins_begin;
  78. /** @brief End index for bins taken care of by this thread. */
  79. _BinIndex __bins_end;
  80. /** @brief Random _M_seed for this thread. */
  81. uint32_t _M_seed;
  82. /** @brief Pointer to global data. */
  83. _DRandomShufflingGlobalData<_RAIter>* _M_sd;
  84. };
  85. /** @brief Generate a random number in @c [0,2^__logp).
  86. * @param __logp Logarithm (basis 2) of the upper range __bound.
  87. * @param __rng Random number generator to use.
  88. */
  89. template<typename _RandomNumberGenerator>
  90. inline int
  91. __random_number_pow2(int __logp, _RandomNumberGenerator& __rng)
  92. { return __rng.__genrand_bits(__logp); }
  93. /** @brief Random shuffle code executed by each thread.
  94. * @param __pus Array of thread-local data records. */
  95. template<typename _RAIter, typename _RandomNumberGenerator>
  96. void
  97. __parallel_random_shuffle_drs_pu(_DRSSorterPU<_RAIter,
  98. _RandomNumberGenerator>* __pus)
  99. {
  100. typedef std::iterator_traits<_RAIter> _TraitsType;
  101. typedef typename _TraitsType::value_type _ValueType;
  102. typedef typename _TraitsType::difference_type _DifferenceType;
  103. _ThreadIndex __iam = omp_get_thread_num();
  104. _DRSSorterPU<_RAIter, _RandomNumberGenerator>* __d = &__pus[__iam];
  105. _DRandomShufflingGlobalData<_RAIter>* __sd = __d->_M_sd;
  106. // Indexing: _M_dist[bin][processor]
  107. _DifferenceType __length = (__sd->_M_starts[__iam + 1]
  108. - __sd->_M_starts[__iam]);
  109. _BinIndex* __oracles = new _BinIndex[__length];
  110. _DifferenceType* __dist = new _DifferenceType[__sd->_M_num_bins + 1];
  111. _BinIndex* __bin_proc = new _BinIndex[__sd->_M_num_bins];
  112. _ValueType** __temporaries = new _ValueType*[__d->_M_num_threads];
  113. // Compute oracles and count appearances.
  114. for (_BinIndex __b = 0; __b < __sd->_M_num_bins + 1; ++__b)
  115. __dist[__b] = 0;
  116. int __num_bits = __sd->_M_num_bits;
  117. _RandomNumber __rng(__d->_M_seed);
  118. // First main loop.
  119. for (_DifferenceType __i = 0; __i < __length; ++__i)
  120. {
  121. _BinIndex __oracle = __random_number_pow2(__num_bits, __rng);
  122. __oracles[__i] = __oracle;
  123. // To allow prefix (partial) sum.
  124. ++(__dist[__oracle + 1]);
  125. }
  126. for (_BinIndex __b = 0; __b < __sd->_M_num_bins + 1; ++__b)
  127. __sd->_M_dist[__b][__iam + 1] = __dist[__b];
  128. # pragma omp barrier
  129. # pragma omp single
  130. {
  131. // Sum up bins, __sd->_M_dist[__s + 1][__d->_M_num_threads] now
  132. // contains the total number of items in bin __s
  133. for (_BinIndex __s = 0; __s < __sd->_M_num_bins; ++__s)
  134. __gnu_sequential::partial_sum(__sd->_M_dist[__s + 1],
  135. __sd->_M_dist[__s + 1]
  136. + __d->_M_num_threads + 1,
  137. __sd->_M_dist[__s + 1]);
  138. }
  139. # pragma omp barrier
  140. _SequenceIndex __offset = 0, __global_offset = 0;
  141. for (_BinIndex __s = 0; __s < __d->_M_bins_begin; ++__s)
  142. __global_offset += __sd->_M_dist[__s + 1][__d->_M_num_threads];
  143. # pragma omp barrier
  144. for (_BinIndex __s = __d->_M_bins_begin; __s < __d->__bins_end; ++__s)
  145. {
  146. for (int __t = 0; __t < __d->_M_num_threads + 1; ++__t)
  147. __sd->_M_dist[__s + 1][__t] += __offset;
  148. __offset = __sd->_M_dist[__s + 1][__d->_M_num_threads];
  149. }
  150. __sd->_M_temporaries[__iam] = static_cast<_ValueType*>
  151. (::operator new(sizeof(_ValueType) * __offset));
  152. # pragma omp barrier
  153. // Draw local copies to avoid false sharing.
  154. for (_BinIndex __b = 0; __b < __sd->_M_num_bins + 1; ++__b)
  155. __dist[__b] = __sd->_M_dist[__b][__iam];
  156. for (_BinIndex __b = 0; __b < __sd->_M_num_bins; ++__b)
  157. __bin_proc[__b] = __sd->_M_bin_proc[__b];
  158. for (_ThreadIndex __t = 0; __t < __d->_M_num_threads; ++__t)
  159. __temporaries[__t] = __sd->_M_temporaries[__t];
  160. _RAIter __source = __sd->_M_source;
  161. _DifferenceType __start = __sd->_M_starts[__iam];
  162. // Distribute according to oracles, second main loop.
  163. for (_DifferenceType __i = 0; __i < __length; ++__i)
  164. {
  165. _BinIndex __target_bin = __oracles[__i];
  166. _ThreadIndex __target_p = __bin_proc[__target_bin];
  167. // Last column [__d->_M_num_threads] stays unchanged.
  168. ::new(&(__temporaries[__target_p][__dist[__target_bin + 1]++]))
  169. _ValueType(*(__source + __i + __start));
  170. }
  171. delete[] __oracles;
  172. delete[] __dist;
  173. delete[] __bin_proc;
  174. delete[] __temporaries;
  175. # pragma omp barrier
  176. // Shuffle bins internally.
  177. for (_BinIndex __b = __d->_M_bins_begin; __b < __d->__bins_end; ++__b)
  178. {
  179. _ValueType* __begin =
  180. (__sd->_M_temporaries[__iam]
  181. + (__b == __d->_M_bins_begin
  182. ? 0 : __sd->_M_dist[__b][__d->_M_num_threads])),
  183. *__end = (__sd->_M_temporaries[__iam]
  184. + __sd->_M_dist[__b + 1][__d->_M_num_threads]);
  185. __sequential_random_shuffle(__begin, __end, __rng);
  186. std::copy(__begin, __end, __sd->_M_source + __global_offset
  187. + (__b == __d->_M_bins_begin
  188. ? 0 : __sd->_M_dist[__b][__d->_M_num_threads]));
  189. }
  190. for (_SequenceIndex __i = 0; __i < __offset; ++__i)
  191. __sd->_M_temporaries[__iam][__i].~_ValueType();
  192. ::operator delete(__sd->_M_temporaries[__iam]);
  193. }
  194. /** @brief Round up to the next greater power of 2.
  195. * @param __x _Integer to round up */
  196. template<typename _Tp>
  197. _Tp
  198. __round_up_to_pow2(_Tp __x)
  199. {
  200. if (__x <= 1)
  201. return 1;
  202. else
  203. return (_Tp)1 << (__rd_log2(__x - 1) + 1);
  204. }
  205. /** @brief Main parallel random shuffle step.
  206. * @param __begin Begin iterator of sequence.
  207. * @param __end End iterator of sequence.
  208. * @param __n Length of sequence.
  209. * @param __num_threads Number of threads to use.
  210. * @param __rng Random number generator to use.
  211. */
  212. template<typename _RAIter, typename _RandomNumberGenerator>
  213. void
  214. __parallel_random_shuffle_drs(_RAIter __begin, _RAIter __end,
  215. typename std::iterator_traits
  216. <_RAIter>::difference_type __n,
  217. _ThreadIndex __num_threads,
  218. _RandomNumberGenerator& __rng)
  219. {
  220. typedef std::iterator_traits<_RAIter> _TraitsType;
  221. typedef typename _TraitsType::value_type _ValueType;
  222. typedef typename _TraitsType::difference_type _DifferenceType;
  223. _GLIBCXX_CALL(__n)
  224. const _Settings& __s = _Settings::get();
  225. if (__num_threads > __n)
  226. __num_threads = static_cast<_ThreadIndex>(__n);
  227. _BinIndex __num_bins, __num_bins_cache;
  228. #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1
  229. // Try the L1 cache first.
  230. // Must fit into L1.
  231. __num_bins_cache =
  232. std::max<_DifferenceType>(1, __n / (__s.L1_cache_size_lb
  233. / sizeof(_ValueType)));
  234. __num_bins_cache = __round_up_to_pow2(__num_bins_cache);
  235. // No more buckets than TLB entries, power of 2
  236. // Power of 2 and at least one element per bin, at most the TLB size.
  237. __num_bins = std::min<_DifferenceType>(__n, __num_bins_cache);
  238. #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB
  239. // 2 TLB entries needed per bin.
  240. __num_bins = std::min<_DifferenceType>(__s.TLB_size / 2, __num_bins);
  241. #endif
  242. __num_bins = __round_up_to_pow2(__num_bins);
  243. if (__num_bins < __num_bins_cache)
  244. {
  245. #endif
  246. // Now try the L2 cache
  247. // Must fit into L2
  248. __num_bins_cache = static_cast<_BinIndex>
  249. (std::max<_DifferenceType>(1, __n / (__s.L2_cache_size
  250. / sizeof(_ValueType))));
  251. __num_bins_cache = __round_up_to_pow2(__num_bins_cache);
  252. // No more buckets than TLB entries, power of 2.
  253. __num_bins = static_cast<_BinIndex>
  254. (std::min(__n, static_cast<_DifferenceType>(__num_bins_cache)));
  255. // Power of 2 and at least one element per bin, at most the TLB size.
  256. #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB
  257. // 2 TLB entries needed per bin.
  258. __num_bins = std::min(static_cast<_DifferenceType>(__s.TLB_size / 2),
  259. __num_bins);
  260. #endif
  261. __num_bins = __round_up_to_pow2(__num_bins);
  262. #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1
  263. }
  264. #endif
  265. __num_bins = __round_up_to_pow2(
  266. std::max<_BinIndex>(__num_threads, __num_bins));
  267. if (__num_threads <= 1)
  268. {
  269. _RandomNumber __derived_rng(
  270. __rng(std::numeric_limits<uint32_t>::max()));
  271. __sequential_random_shuffle(__begin, __end, __derived_rng);
  272. return;
  273. }
  274. _DRandomShufflingGlobalData<_RAIter> __sd(__begin);
  275. _DRSSorterPU<_RAIter, _RandomNumber >* __pus;
  276. _DifferenceType* __starts;
  277. # pragma omp parallel num_threads(__num_threads)
  278. {
  279. _ThreadIndex __num_threads = omp_get_num_threads();
  280. # pragma omp single
  281. {
  282. __pus = new _DRSSorterPU<_RAIter, _RandomNumber>[__num_threads];
  283. __sd._M_temporaries = new _ValueType*[__num_threads];
  284. __sd._M_dist = new _DifferenceType*[__num_bins + 1];
  285. __sd._M_bin_proc = new _ThreadIndex[__num_bins];
  286. for (_BinIndex __b = 0; __b < __num_bins + 1; ++__b)
  287. __sd._M_dist[__b] = new _DifferenceType[__num_threads + 1];
  288. for (_BinIndex __b = 0; __b < (__num_bins + 1); ++__b)
  289. {
  290. __sd._M_dist[0][0] = 0;
  291. __sd._M_dist[__b][0] = 0;
  292. }
  293. __starts = __sd._M_starts = new _DifferenceType[__num_threads + 1];
  294. int __bin_cursor = 0;
  295. __sd._M_num_bins = __num_bins;
  296. __sd._M_num_bits = __rd_log2(__num_bins);
  297. _DifferenceType __chunk_length = __n / __num_threads,
  298. __split = __n % __num_threads,
  299. __start = 0;
  300. _DifferenceType __bin_chunk_length = __num_bins / __num_threads,
  301. __bin_split = __num_bins % __num_threads;
  302. for (_ThreadIndex __i = 0; __i < __num_threads; ++__i)
  303. {
  304. __starts[__i] = __start;
  305. __start += (__i < __split
  306. ? (__chunk_length + 1) : __chunk_length);
  307. int __j = __pus[__i]._M_bins_begin = __bin_cursor;
  308. // Range of bins for this processor.
  309. __bin_cursor += (__i < __bin_split
  310. ? (__bin_chunk_length + 1)
  311. : __bin_chunk_length);
  312. __pus[__i].__bins_end = __bin_cursor;
  313. for (; __j < __bin_cursor; ++__j)
  314. __sd._M_bin_proc[__j] = __i;
  315. __pus[__i]._M_num_threads = __num_threads;
  316. __pus[__i]._M_seed = __rng(std::numeric_limits<uint32_t>::max());
  317. __pus[__i]._M_sd = &__sd;
  318. }
  319. __starts[__num_threads] = __start;
  320. } //single
  321. // Now shuffle in parallel.
  322. __parallel_random_shuffle_drs_pu(__pus);
  323. } // parallel
  324. delete[] __starts;
  325. delete[] __sd._M_bin_proc;
  326. for (int __s = 0; __s < (__num_bins + 1); ++__s)
  327. delete[] __sd._M_dist[__s];
  328. delete[] __sd._M_dist;
  329. delete[] __sd._M_temporaries;
  330. delete[] __pus;
  331. }
  332. /** @brief Sequential cache-efficient random shuffle.
  333. * @param __begin Begin iterator of sequence.
  334. * @param __end End iterator of sequence.
  335. * @param __rng Random number generator to use.
  336. */
  337. template<typename _RAIter, typename _RandomNumberGenerator>
  338. void
  339. __sequential_random_shuffle(_RAIter __begin, _RAIter __end,
  340. _RandomNumberGenerator& __rng)
  341. {
  342. typedef std::iterator_traits<_RAIter> _TraitsType;
  343. typedef typename _TraitsType::value_type _ValueType;
  344. typedef typename _TraitsType::difference_type _DifferenceType;
  345. _DifferenceType __n = __end - __begin;
  346. const _Settings& __s = _Settings::get();
  347. _BinIndex __num_bins, __num_bins_cache;
  348. #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1
  349. // Try the L1 cache first, must fit into L1.
  350. __num_bins_cache = std::max<_DifferenceType>
  351. (1, __n / (__s.L1_cache_size_lb / sizeof(_ValueType)));
  352. __num_bins_cache = __round_up_to_pow2(__num_bins_cache);
  353. // No more buckets than TLB entries, power of 2
  354. // Power of 2 and at least one element per bin, at most the TLB size
  355. __num_bins = std::min(__n, (_DifferenceType)__num_bins_cache);
  356. #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB
  357. // 2 TLB entries needed per bin
  358. __num_bins = std::min((_DifferenceType)__s.TLB_size / 2, __num_bins);
  359. #endif
  360. __num_bins = __round_up_to_pow2(__num_bins);
  361. if (__num_bins < __num_bins_cache)
  362. {
  363. #endif
  364. // Now try the L2 cache, must fit into L2.
  365. __num_bins_cache = static_cast<_BinIndex>
  366. (std::max<_DifferenceType>(1, __n / (__s.L2_cache_size
  367. / sizeof(_ValueType))));
  368. __num_bins_cache = __round_up_to_pow2(__num_bins_cache);
  369. // No more buckets than TLB entries, power of 2
  370. // Power of 2 and at least one element per bin, at most the TLB size.
  371. __num_bins = static_cast<_BinIndex>
  372. (std::min(__n, static_cast<_DifferenceType>(__num_bins_cache)));
  373. #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB
  374. // 2 TLB entries needed per bin
  375. __num_bins = std::min<_DifferenceType>(__s.TLB_size / 2, __num_bins);
  376. #endif
  377. __num_bins = __round_up_to_pow2(__num_bins);
  378. #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1
  379. }
  380. #endif
  381. int __num_bits = __rd_log2(__num_bins);
  382. if (__num_bins > 1)
  383. {
  384. _ValueType* __target =
  385. static_cast<_ValueType*>(::operator new(sizeof(_ValueType) * __n));
  386. _BinIndex* __oracles = new _BinIndex[__n];
  387. _DifferenceType* __dist0 = new _DifferenceType[__num_bins + 1],
  388. * __dist1 = new _DifferenceType[__num_bins + 1];
  389. for (int __b = 0; __b < __num_bins + 1; ++__b)
  390. __dist0[__b] = 0;
  391. _RandomNumber __bitrng(__rng(0xFFFFFFFF));
  392. for (_DifferenceType __i = 0; __i < __n; ++__i)
  393. {
  394. _BinIndex __oracle = __random_number_pow2(__num_bits, __bitrng);
  395. __oracles[__i] = __oracle;
  396. // To allow prefix (partial) sum.
  397. ++(__dist0[__oracle + 1]);
  398. }
  399. // Sum up bins.
  400. __gnu_sequential::partial_sum(__dist0, __dist0 + __num_bins + 1,
  401. __dist0);
  402. for (int __b = 0; __b < __num_bins + 1; ++__b)
  403. __dist1[__b] = __dist0[__b];
  404. // Distribute according to oracles.
  405. for (_DifferenceType __i = 0; __i < __n; ++__i)
  406. ::new(&(__target[(__dist0[__oracles[__i]])++]))
  407. _ValueType(*(__begin + __i));
  408. for (int __b = 0; __b < __num_bins; ++__b)
  409. __sequential_random_shuffle(__target + __dist1[__b],
  410. __target + __dist1[__b + 1], __rng);
  411. // Copy elements back.
  412. std::copy(__target, __target + __n, __begin);
  413. delete[] __dist0;
  414. delete[] __dist1;
  415. delete[] __oracles;
  416. for (_DifferenceType __i = 0; __i < __n; ++__i)
  417. __target[__i].~_ValueType();
  418. ::operator delete(__target);
  419. }
  420. else
  421. __gnu_sequential::random_shuffle(__begin, __end, __rng);
  422. }
  423. /** @brief Parallel random public call.
  424. * @param __begin Begin iterator of sequence.
  425. * @param __end End iterator of sequence.
  426. * @param __rng Random number generator to use.
  427. */
  428. template<typename _RAIter, typename _RandomNumberGenerator>
  429. inline void
  430. __parallel_random_shuffle(_RAIter __begin, _RAIter __end,
  431. _RandomNumberGenerator __rng = _RandomNumber())
  432. {
  433. typedef std::iterator_traits<_RAIter> _TraitsType;
  434. typedef typename _TraitsType::difference_type _DifferenceType;
  435. _DifferenceType __n = __end - __begin;
  436. __parallel_random_shuffle_drs(__begin, __end, __n,
  437. __get_max_threads(), __rng);
  438. }
  439. }
  440. #endif /* _GLIBCXX_PARALLEL_RANDOM_SHUFFLE_H */