Update Copyright years for files modified in 2010.
[official-gcc.git] / libstdc++-v3 / include / parallel / random_shuffle.h
blobbae95724966b8462fd924f366062e1cd8c4a155b
1 // -*- C++ -*-
3 // Copyright (C) 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
4 //
5 // This file is part of the GNU ISO C++ Library. This library is free
6 // software; you can redistribute it and/or modify it under the terms
7 // of the GNU General Public License as published by the Free Software
8 // Foundation; either version 3, or (at your option) any later
9 // version.
11 // This library is distributed in the hope that it will be useful, but
12 // WITHOUT ANY WARRANTY; without even the implied warranty of
13 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 // General Public License for more details.
16 // Under Section 7 of GPL version 3, you are granted additional
17 // permissions described in the GCC Runtime Library Exception, version
18 // 3.1, as published by the Free Software Foundation.
20 // You should have received a copy of the GNU General Public License and
21 // a copy of the GCC Runtime Library Exception along with this program;
22 // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see
23 // <http://www.gnu.org/licenses/>.
25 /** @file parallel/random_shuffle.h
26 * @brief Parallel implementation of std::random_shuffle().
27 * This file is a GNU parallel extension to the Standard C++ Library.
30 // Written by Johannes Singler.
32 #ifndef _GLIBCXX_PARALLEL_RANDOM_SHUFFLE_H
33 #define _GLIBCXX_PARALLEL_RANDOM_SHUFFLE_H 1
35 #include <limits>
36 #include <bits/stl_numeric.h>
37 #include <parallel/parallel.h>
38 #include <parallel/random_number.h>
40 namespace __gnu_parallel
42 /** @brief Type to hold the index of a bin.
44 * Since many variables of this type are allocated, it should be
45 * chosen as small as possible.
47 typedef unsigned short _BinIndex;
49 /** @brief Data known to every thread participating in
50 __gnu_parallel::__parallel_random_shuffle(). */
51 template<typename _RAIter>
52 struct _DRandomShufflingGlobalData
54 typedef std::iterator_traits<_RAIter> _TraitsType;
55 typedef typename _TraitsType::value_type _ValueType;
56 typedef typename _TraitsType::difference_type _DifferenceType;
58 /** @brief Begin iterator of the __source. */
59 _RAIter& _M_source;
61 /** @brief Temporary arrays for each thread. */
62 _ValueType** _M_temporaries;
64 /** @brief Two-dimensional array to hold the thread-bin distribution.
66 * Dimensions (_M_num_threads + 1) __x (_M_num_bins + 1). */
67 _DifferenceType** _M_dist;
69 /** @brief Start indexes of the threads' __chunks. */
70 _DifferenceType* _M_starts;
72 /** @brief Number of the thread that will further process the
73 corresponding bin. */
74 _ThreadIndex* _M_bin_proc;
76 /** @brief Number of bins to distribute to. */
77 int _M_num_bins;
79 /** @brief Number of bits needed to address the bins. */
80 int _M_num_bits;
82 /** @brief Constructor. */
83 _DRandomShufflingGlobalData(_RAIter& __source)
84 : _M_source(__source) { }
87 /** @brief Local data for a thread participating in
88 __gnu_parallel::__parallel_random_shuffle().
90 template<typename _RAIter, typename _RandomNumberGenerator>
91 struct _DRSSorterPU
93 /** @brief Number of threads participating in total. */
94 int _M_num_threads;
96 /** @brief Begin index for bins taken care of by this thread. */
97 _BinIndex _M_bins_begin;
99 /** @brief End index for bins taken care of by this thread. */
100 _BinIndex __bins_end;
102 /** @brief Random _M_seed for this thread. */
103 uint32_t _M_seed;
105 /** @brief Pointer to global data. */
106 _DRandomShufflingGlobalData<_RAIter>* _M_sd;
109 /** @brief Generate a random number in @c [0,2^__logp).
110 * @param __logp Logarithm (basis 2) of the upper range __bound.
111 * @param __rng Random number generator to use.
113 template<typename _RandomNumberGenerator>
114 inline int
115 __random_number_pow2(int __logp, _RandomNumberGenerator& __rng)
116 { return __rng.__genrand_bits(__logp); }
118 /** @brief Random shuffle code executed by each thread.
119 * @param __pus Array of thread-local data records. */
120 template<typename _RAIter, typename _RandomNumberGenerator>
121 void
122 __parallel_random_shuffle_drs_pu(_DRSSorterPU<_RAIter,
123 _RandomNumberGenerator>* __pus)
125 typedef std::iterator_traits<_RAIter> _TraitsType;
126 typedef typename _TraitsType::value_type _ValueType;
127 typedef typename _TraitsType::difference_type _DifferenceType;
129 _ThreadIndex __iam = omp_get_thread_num();
130 _DRSSorterPU<_RAIter, _RandomNumberGenerator>* __d = &__pus[__iam];
131 _DRandomShufflingGlobalData<_RAIter>* __sd = __d->_M_sd;
133 // Indexing: _M_dist[bin][processor]
134 _DifferenceType __length = (__sd->_M_starts[__iam + 1]
135 - __sd->_M_starts[__iam]);
136 _BinIndex* __oracles = new _BinIndex[__length];
137 _DifferenceType* __dist = new _DifferenceType[__sd->_M_num_bins + 1];
138 _BinIndex* __bin_proc = new _BinIndex[__sd->_M_num_bins];
139 _ValueType** __temporaries = new _ValueType*[__d->_M_num_threads];
141 // Compute oracles and count appearances.
142 for (_BinIndex __b = 0; __b < __sd->_M_num_bins + 1; ++__b)
143 __dist[__b] = 0;
144 int __num_bits = __sd->_M_num_bits;
146 _RandomNumber __rng(__d->_M_seed);
148 // First main loop.
149 for (_DifferenceType __i = 0; __i < __length; ++__i)
151 _BinIndex __oracle = __random_number_pow2(__num_bits, __rng);
152 __oracles[__i] = __oracle;
154 // To allow prefix (partial) sum.
155 ++(__dist[__oracle + 1]);
158 for (_BinIndex __b = 0; __b < __sd->_M_num_bins + 1; ++__b)
159 __sd->_M_dist[__b][__iam + 1] = __dist[__b];
161 # pragma omp barrier
163 # pragma omp single
165 // Sum up bins, __sd->_M_dist[__s + 1][__d->_M_num_threads] now
166 // contains the total number of items in bin __s
167 for (_BinIndex __s = 0; __s < __sd->_M_num_bins; ++__s)
168 __gnu_sequential::partial_sum(__sd->_M_dist[__s + 1],
169 __sd->_M_dist[__s + 1]
170 + __d->_M_num_threads + 1,
171 __sd->_M_dist[__s + 1]);
174 # pragma omp barrier
176 _SequenceIndex __offset = 0, __global_offset = 0;
177 for (_BinIndex __s = 0; __s < __d->_M_bins_begin; ++__s)
178 __global_offset += __sd->_M_dist[__s + 1][__d->_M_num_threads];
180 # pragma omp barrier
182 for (_BinIndex __s = __d->_M_bins_begin; __s < __d->__bins_end; ++__s)
184 for (int __t = 0; __t < __d->_M_num_threads + 1; ++__t)
185 __sd->_M_dist[__s + 1][__t] += __offset;
186 __offset = __sd->_M_dist[__s + 1][__d->_M_num_threads];
189 __sd->_M_temporaries[__iam] = static_cast<_ValueType*>
190 (::operator new(sizeof(_ValueType) * __offset));
192 # pragma omp barrier
194 // Draw local copies to avoid false sharing.
195 for (_BinIndex __b = 0; __b < __sd->_M_num_bins + 1; ++__b)
196 __dist[__b] = __sd->_M_dist[__b][__iam];
197 for (_BinIndex __b = 0; __b < __sd->_M_num_bins; ++__b)
198 __bin_proc[__b] = __sd->_M_bin_proc[__b];
199 for (_ThreadIndex __t = 0; __t < __d->_M_num_threads; ++__t)
200 __temporaries[__t] = __sd->_M_temporaries[__t];
202 _RAIter __source = __sd->_M_source;
203 _DifferenceType __start = __sd->_M_starts[__iam];
205 // Distribute according to oracles, second main loop.
206 for (_DifferenceType __i = 0; __i < __length; ++__i)
208 _BinIndex __target_bin = __oracles[__i];
209 _ThreadIndex __target_p = __bin_proc[__target_bin];
211 // Last column [__d->_M_num_threads] stays unchanged.
212 ::new(&(__temporaries[__target_p][__dist[__target_bin + 1]++]))
213 _ValueType(*(__source + __i + __start));
216 delete[] __oracles;
217 delete[] __dist;
218 delete[] __bin_proc;
219 delete[] __temporaries;
221 # pragma omp barrier
223 // Shuffle bins internally.
224 for (_BinIndex __b = __d->_M_bins_begin; __b < __d->__bins_end; ++__b)
226 _ValueType* __begin =
227 (__sd->_M_temporaries[__iam]
228 + (__b == __d->_M_bins_begin
229 ? 0 : __sd->_M_dist[__b][__d->_M_num_threads])),
230 * __end = (__sd->_M_temporaries[__iam]
231 + __sd->_M_dist[__b + 1][__d->_M_num_threads]);
233 __sequential_random_shuffle(__begin, __end, __rng);
234 std::copy(__begin, __end, __sd->_M_source + __global_offset
235 + (__b == __d->_M_bins_begin
236 ? 0 : __sd->_M_dist[__b][__d->_M_num_threads]));
239 ::operator delete(__sd->_M_temporaries[__iam]);
242 /** @brief Round up to the next greater power of 2.
243 * @param __x _Integer to round up */
244 template<typename _Tp>
245 _Tp
246 __round_up_to_pow2(_Tp __x)
248 if (__x <= 1)
249 return 1;
250 else
251 return (_Tp)1 << (__rd_log2(__x - 1) + 1);
254 /** @brief Main parallel random shuffle step.
255 * @param __begin Begin iterator of sequence.
256 * @param __end End iterator of sequence.
257 * @param __n Length of sequence.
258 * @param __num_threads Number of threads to use.
259 * @param __rng Random number generator to use.
261 template<typename _RAIter, typename _RandomNumberGenerator>
262 void
263 __parallel_random_shuffle_drs(_RAIter __begin, _RAIter __end,
264 typename std::iterator_traits
265 <_RAIter>::difference_type __n,
266 _ThreadIndex __num_threads,
267 _RandomNumberGenerator& __rng)
269 typedef std::iterator_traits<_RAIter> _TraitsType;
270 typedef typename _TraitsType::value_type _ValueType;
271 typedef typename _TraitsType::difference_type _DifferenceType;
273 _GLIBCXX_CALL(__n)
275 const _Settings& __s = _Settings::get();
277 if (__num_threads > __n)
278 __num_threads = static_cast<_ThreadIndex>(__n);
280 _BinIndex __num_bins, __num_bins_cache;
282 #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1
283 // Try the L1 cache first.
285 // Must fit into L1.
286 __num_bins_cache =
287 std::max<_DifferenceType>(1, __n / (__s.L1_cache_size_lb
288 / sizeof(_ValueType)));
289 __num_bins_cache = __round_up_to_pow2(__num_bins_cache);
291 // No more buckets than TLB entries, power of 2
292 // Power of 2 and at least one element per bin, at most the TLB size.
293 __num_bins = std::min<_DifferenceType>(__n, __num_bins_cache);
295 #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB
296 // 2 TLB entries needed per bin.
297 __num_bins = std::min<_DifferenceType>(__s.TLB_size / 2, __num_bins);
298 #endif
299 __num_bins = __round_up_to_pow2(__num_bins);
301 if (__num_bins < __num_bins_cache)
303 #endif
304 // Now try the L2 cache
305 // Must fit into L2
306 __num_bins_cache = static_cast<_BinIndex>
307 (std::max<_DifferenceType>(1, __n / (__s.L2_cache_size
308 / sizeof(_ValueType))));
309 __num_bins_cache = __round_up_to_pow2(__num_bins_cache);
311 // No more buckets than TLB entries, power of 2.
312 __num_bins = static_cast<_BinIndex>
313 (std::min(__n, static_cast<_DifferenceType>(__num_bins_cache)));
314 // Power of 2 and at least one element per bin, at most the TLB size.
315 #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB
316 // 2 TLB entries needed per bin.
317 __num_bins = std::min(static_cast<_DifferenceType>(__s.TLB_size / 2),
318 __num_bins);
319 #endif
320 __num_bins = __round_up_to_pow2(__num_bins);
321 #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1
323 #endif
325 __num_bins = __round_up_to_pow2(
326 std::max<_BinIndex>(__num_threads, __num_bins));
328 if (__num_threads <= 1)
330 _RandomNumber __derived_rng(
331 __rng(std::numeric_limits<uint32_t>::max()));
332 __sequential_random_shuffle(__begin, __end, __derived_rng);
333 return;
336 _DRandomShufflingGlobalData<_RAIter> __sd(__begin);
337 _DRSSorterPU<_RAIter, _RandomNumber >* __pus;
338 _DifferenceType* __starts;
340 # pragma omp parallel num_threads(__num_threads)
342 _ThreadIndex __num_threads = omp_get_num_threads();
343 # pragma omp single
345 __pus = new _DRSSorterPU<_RAIter, _RandomNumber>[__num_threads];
347 __sd._M_temporaries = new _ValueType*[__num_threads];
348 __sd._M_dist = new _DifferenceType*[__num_bins + 1];
349 __sd._M_bin_proc = new _ThreadIndex[__num_bins];
350 for (_BinIndex __b = 0; __b < __num_bins + 1; ++__b)
351 __sd._M_dist[__b] = new _DifferenceType[__num_threads + 1];
352 for (_BinIndex __b = 0; __b < (__num_bins + 1); ++__b)
354 __sd._M_dist[0][0] = 0;
355 __sd._M_dist[__b][0] = 0;
357 __starts = __sd._M_starts = new _DifferenceType[__num_threads + 1];
358 int __bin_cursor = 0;
359 __sd._M_num_bins = __num_bins;
360 __sd._M_num_bits = __rd_log2(__num_bins);
362 _DifferenceType __chunk_length = __n / __num_threads,
363 __split = __n % __num_threads,
364 __start = 0;
365 _DifferenceType __bin_chunk_length = __num_bins / __num_threads,
366 __bin_split = __num_bins % __num_threads;
367 for (_ThreadIndex __i = 0; __i < __num_threads; ++__i)
369 __starts[__i] = __start;
370 __start += (__i < __split
371 ? (__chunk_length + 1) : __chunk_length);
372 int __j = __pus[__i]._M_bins_begin = __bin_cursor;
374 // Range of bins for this processor.
375 __bin_cursor += (__i < __bin_split
376 ? (__bin_chunk_length + 1)
377 : __bin_chunk_length);
378 __pus[__i].__bins_end = __bin_cursor;
379 for (; __j < __bin_cursor; ++__j)
380 __sd._M_bin_proc[__j] = __i;
381 __pus[__i]._M_num_threads = __num_threads;
382 __pus[__i]._M_seed = __rng(std::numeric_limits<uint32_t>::max());
383 __pus[__i]._M_sd = &__sd;
385 __starts[__num_threads] = __start;
386 } //single
387 // Now shuffle in parallel.
388 __parallel_random_shuffle_drs_pu(__pus);
389 } // parallel
391 delete[] __starts;
392 delete[] __sd._M_bin_proc;
393 for (int __s = 0; __s < (__num_bins + 1); ++__s)
394 delete[] __sd._M_dist[__s];
395 delete[] __sd._M_dist;
396 delete[] __sd._M_temporaries;
398 delete[] __pus;
401 /** @brief Sequential cache-efficient random shuffle.
402 * @param __begin Begin iterator of sequence.
403 * @param __end End iterator of sequence.
404 * @param __rng Random number generator to use.
406 template<typename _RAIter, typename _RandomNumberGenerator>
407 void
408 __sequential_random_shuffle(_RAIter __begin, _RAIter __end,
409 _RandomNumberGenerator& __rng)
411 typedef std::iterator_traits<_RAIter> _TraitsType;
412 typedef typename _TraitsType::value_type _ValueType;
413 typedef typename _TraitsType::difference_type _DifferenceType;
415 _DifferenceType __n = __end - __begin;
416 const _Settings& __s = _Settings::get();
418 _BinIndex __num_bins, __num_bins_cache;
420 #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1
421 // Try the L1 cache first, must fit into L1.
422 __num_bins_cache = std::max<_DifferenceType>
423 (1, __n / (__s.L1_cache_size_lb / sizeof(_ValueType)));
424 __num_bins_cache = __round_up_to_pow2(__num_bins_cache);
426 // No more buckets than TLB entries, power of 2
427 // Power of 2 and at least one element per bin, at most the TLB size
428 __num_bins = std::min(__n, (_DifferenceType)__num_bins_cache);
429 #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB
430 // 2 TLB entries needed per bin
431 __num_bins = std::min((_DifferenceType)__s.TLB_size / 2, __num_bins);
432 #endif
433 __num_bins = __round_up_to_pow2(__num_bins);
435 if (__num_bins < __num_bins_cache)
437 #endif
438 // Now try the L2 cache, must fit into L2.
439 __num_bins_cache = static_cast<_BinIndex>
440 (std::max<_DifferenceType>(1, __n / (__s.L2_cache_size
441 / sizeof(_ValueType))));
442 __num_bins_cache = __round_up_to_pow2(__num_bins_cache);
444 // No more buckets than TLB entries, power of 2
445 // Power of 2 and at least one element per bin, at most the TLB size.
446 __num_bins = static_cast<_BinIndex>
447 (std::min(__n, static_cast<_DifferenceType>(__num_bins_cache)));
449 #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_TLB
450 // 2 TLB entries needed per bin
451 __num_bins = std::min<_DifferenceType>(__s.TLB_size / 2, __num_bins);
452 #endif
453 __num_bins = __round_up_to_pow2(__num_bins);
454 #if _GLIBCXX_RANDOM_SHUFFLE_CONSIDER_L1
456 #endif
458 int __num_bits = __rd_log2(__num_bins);
460 if (__num_bins > 1)
462 _ValueType* __target =
463 static_cast<_ValueType*>(::operator new(sizeof(_ValueType) * __n));
464 _BinIndex* __oracles = new _BinIndex[__n];
465 _DifferenceType* __dist0 = new _DifferenceType[__num_bins + 1],
466 * __dist1 = new _DifferenceType[__num_bins + 1];
468 for (int __b = 0; __b < __num_bins + 1; ++__b)
469 __dist0[__b] = 0;
471 _RandomNumber __bitrng(__rng(0xFFFFFFFF));
473 for (_DifferenceType __i = 0; __i < __n; ++__i)
475 _BinIndex __oracle = __random_number_pow2(__num_bits, __bitrng);
476 __oracles[__i] = __oracle;
478 // To allow prefix (partial) sum.
479 ++(__dist0[__oracle + 1]);
482 // Sum up bins.
483 __gnu_sequential::partial_sum(__dist0, __dist0 + __num_bins + 1,
484 __dist0);
486 for (int __b = 0; __b < __num_bins + 1; ++__b)
487 __dist1[__b] = __dist0[__b];
489 // Distribute according to oracles.
490 for (_DifferenceType __i = 0; __i < __n; ++__i)
491 ::new(&(__target[(__dist0[__oracles[__i]])++]))
492 _ValueType(*(__begin + __i));
494 for (int __b = 0; __b < __num_bins; ++__b)
495 __sequential_random_shuffle(__target + __dist1[__b],
496 __target + __dist1[__b + 1], __rng);
498 // Copy elements back.
499 std::copy(__target, __target + __n, __begin);
501 delete[] __dist0;
502 delete[] __dist1;
503 delete[] __oracles;
504 ::operator delete(__target);
506 else
507 __gnu_sequential::random_shuffle(__begin, __end, __rng);
510 /** @brief Parallel random public call.
511 * @param __begin Begin iterator of sequence.
512 * @param __end End iterator of sequence.
513 * @param __rng Random number generator to use.
515 template<typename _RAIter, typename _RandomNumberGenerator>
516 inline void
517 __parallel_random_shuffle(_RAIter __begin, _RAIter __end,
518 _RandomNumberGenerator __rng = _RandomNumber())
520 typedef std::iterator_traits<_RAIter> _TraitsType;
521 typedef typename _TraitsType::difference_type _DifferenceType;
522 _DifferenceType __n = __end - __begin;
523 __parallel_random_shuffle_drs(__begin, __end, __n,
524 __get_max_threads(), __rng);
528 #endif /* _GLIBCXX_PARALLEL_RANDOM_SHUFFLE_H */