1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
|
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
* This file is part of the LibreOffice project.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#ifndef INCLUDED_COMPHELPER_PARALLELSORT_HXX
#define INCLUDED_COMPHELPER_PARALLELSORT_HXX
#include <comphelper/threadpool.hxx>
#include <tools/cpuid.hxx>
#include <memory>
#include <iterator>
#include <thread>
#include <algorithm>
#include <cmath>
#include <random>
#include <functional>
#include <iostream>
#include <chrono>
namespace comphelper
{
const size_t nThreadCountGlobal = std::thread::hardware_concurrency();
const bool bHyperThreadingActive = cpuid::hasHyperThreading();
static comphelper::ThreadPool& rTPool(comphelper::ThreadPool::getSharedOptimalPool());
static thread_local std::mt19937 aGenerator{ std::random_device{}() };
#define PARALLELSORT_ENABLEPZ 0
namespace
{
class ProfileZone
{
public:
#if PARALLELSORT_ENABLEPZ
ProfileZone(const char* pTag)
: maTag(pTag)
, maStart(std::chrono::steady_clock::now())
, mbFinished(false)
{
}
~ProfileZone()
{
if (!mbFinished)
showTimeElapsed();
}
void stop()
{
showTimeElapsed();
mbFinished = true;
}
#else
ProfileZone(const char* /*pTag*/)
: mbDummy(true)
{
}
void stop()
{
// Avoid loplugin:staticmethods, loplugin:staticaccess errors
(void)mbDummy;
}
#endif
private:
#if PARALLELSORT_ENABLEPZ
void showTimeElapsed()
{
auto end = std::chrono::steady_clock::now();
size_t elapsed
= std::chrono::duration_cast<std::chrono::milliseconds>(end - maStart).count();
std::cout << maTag << " : " << elapsed << " ms" << std::endl << std::flush;
}
std::string maTag;
std::chrono::steady_clock::time_point maStart;
bool mbFinished;
#else
bool mbDummy;
#endif
};
class ParallelRunner
{
class Executor final : public comphelper::ThreadTask
{
public:
Executor(const std::shared_ptr<comphelper::ThreadTaskTag>& rTag,
std::function<void()> aFunc)
: comphelper::ThreadTask(rTag)
, maFunc(std::move(aFunc))
{
}
virtual void doWork() override { maFunc(); }
private:
const std::function<void()> maFunc;
};
public:
ParallelRunner() { maTag = comphelper::ThreadPool::createThreadTaskTag(); }
void enqueue(std::function<void()> aFunc)
{
rTPool.pushTask(std::make_unique<Executor>(maTag, aFunc));
}
void wait() { rTPool.waitUntilDone(maTag, false); }
private:
std::shared_ptr<comphelper::ThreadTaskTag> maTag;
};
constexpr size_t nMaxTreeArraySize = 64;
size_t lcl_round_down_pow2(size_t nNum)
{
size_t nPow2;
for (nPow2 = 1; nPow2 <= nNum; nPow2 <<= 1)
;
return std::min((nPow2 >> 1), nMaxTreeArraySize);
}
template <class RandItr> struct Sampler
{
using ValueType = typename std::iterator_traits<RandItr>::value_type;
static void sample(RandItr aBegin, RandItr aEnd, ValueType* pSamples, size_t nSamples,
size_t /*nParallelism*/)
{
ProfileZone aZone("\tsample()");
assert(aBegin <= aEnd);
size_t nLen = static_cast<std::size_t>(aEnd - aBegin);
assert(std::mt19937::max() >= nLen);
for (size_t nIdx = 0; nIdx < nSamples; ++nIdx)
{
size_t nSel = aGenerator() % nLen--;
using namespace std;
swap(*(aBegin + nSel), *(aBegin + nLen));
pSamples[nIdx] = *(aBegin + nLen);
}
}
};
template <class RandItr, class Compare> class Binner
{
using ValueType = typename std::iterator_traits<RandItr>::value_type;
const size_t mnTreeArraySize;
const size_t mnDividers;
constexpr static size_t mnMaxStaticSize = 1024 * 50;
uint8_t maLabels[mnMaxStaticSize];
ValueType maDividers[nMaxTreeArraySize];
std::unique_ptr<uint8_t[]> pLabels;
size_t maSepBinEnds[nMaxTreeArraySize * nMaxTreeArraySize];
bool mbThreaded;
public:
size_t maBinEnds[nMaxTreeArraySize];
Binner(const ValueType* pSamples, size_t nSamples, size_t nBins, bool bThreaded)
: mnTreeArraySize(lcl_round_down_pow2(nBins))
, mnDividers(mnTreeArraySize - 1)
, mbThreaded(bThreaded)
{
assert((nSamples % mnTreeArraySize) == 0);
assert(mnTreeArraySize <= nMaxTreeArraySize);
std::fill(maBinEnds, maBinEnds + mnTreeArraySize, 0);
std::fill(maSepBinEnds, maSepBinEnds + mnTreeArraySize * mnTreeArraySize, 0);
fillTreeArray(1, pSamples, pSamples + nSamples);
}
void fillTreeArray(size_t nPos, const ValueType* pLow, const ValueType* pHigh)
{
assert(pLow <= pHigh);
const ValueType* pMid = pLow + (pHigh - pLow) / 2;
maDividers[nPos] = *pMid;
if (2 * nPos < mnDividers) // So that 2*nPos < mnTreeArraySize
{
fillTreeArray(2 * nPos, pLow, pMid);
fillTreeArray(2 * nPos + 1, pMid + 1, pHigh);
}
}
constexpr inline size_t findBin(const ValueType& rVal, Compare& aComp)
{
size_t nIdx = 1;
while (nIdx <= mnDividers)
nIdx = ((nIdx << 1) + aComp(maDividers[nIdx], rVal));
return (nIdx - mnTreeArraySize);
}
void label(const RandItr aBegin, const RandItr aEnd, Compare& aComp)
{
ProfileZone aZoneSetup("\tlabel():setup");
size_t nLen = static_cast<std::size_t>(aEnd - aBegin);
if (nLen > mnMaxStaticSize)
pLabels = std::make_unique<uint8_t[]>(nLen);
uint8_t* pLabelsRaw = (nLen > mnMaxStaticSize) ? pLabels.get() : maLabels;
aZoneSetup.stop();
ProfileZone aZoneFindBins("\tFindBins()");
if (mbThreaded)
{
ParallelRunner aPRunner;
const size_t nBins = mnTreeArraySize;
for (size_t nTIdx = 0; nTIdx < nBins; ++nTIdx)
{
aPRunner.enqueue([this, nTIdx, nBins, nLen, aBegin, pLabelsRaw, &aComp] {
ProfileZone aZoneIn("\t\tFindBinsThreaded()");
size_t nBinEndsStartIdx = nTIdx * mnTreeArraySize;
size_t* pBinEnds = maSepBinEnds + nBinEndsStartIdx;
size_t aBinEndsF[nMaxTreeArraySize] = { 0 };
for (size_t nIdx = nTIdx; nIdx < nLen; nIdx += nBins)
{
size_t nBinIdx = findBin(*(aBegin + nIdx), aComp);
pLabelsRaw[nIdx] = static_cast<uint8_t>(nBinIdx);
++aBinEndsF[nBinIdx];
}
for (size_t nIdx = 0; nIdx < mnTreeArraySize; ++nIdx)
pBinEnds[nIdx] = aBinEndsF[nIdx];
});
}
aPRunner.wait();
// Populate maBinEnds from maSepBinEnds
for (size_t nTIdx = 0; nTIdx < mnTreeArraySize; ++nTIdx)
{
for (size_t nSepIdx = 0; nSepIdx < mnTreeArraySize; ++nSepIdx)
maBinEnds[nTIdx] += maSepBinEnds[nSepIdx * mnTreeArraySize + nTIdx];
}
}
else
{
uint8_t* pLabel = pLabelsRaw;
for (RandItr aItr = aBegin; aItr != aEnd; ++aItr)
{
size_t nBinIdx = findBin(*aItr, aComp);
*pLabel++ = nBinIdx;
++maBinEnds[nBinIdx];
}
}
aZoneFindBins.stop();
size_t nSum = 0;
// Store each bin's starting position in maBinEnds array for now.
for (size_t nIdx = 0; nIdx < mnTreeArraySize; ++nIdx)
{
size_t nSize = maBinEnds[nIdx];
maBinEnds[nIdx] = nSum;
nSum += nSize;
}
// Now maBinEnds has end positions of each bin.
}
void bin(const RandItr aBegin, const RandItr aEnd, ValueType* pOut)
{
ProfileZone aZone("\tbin()");
const size_t nLen = static_cast<std::size_t>(aEnd - aBegin);
uint8_t* pLabelsRaw = (nLen > mnMaxStaticSize) ? pLabels.get() : maLabels;
size_t nIdx;
for (nIdx = 0; nIdx < nLen; ++nIdx)
{
pOut[maBinEnds[pLabelsRaw[nIdx]]++] = *(aBegin + nIdx);
}
}
};
template <class RandItr, class Compare = std::less<>>
void s3sort(const RandItr aBegin, const RandItr aEnd, Compare aComp = Compare(),
bool bThreaded = true)
{
static size_t nThreadCount = nThreadCountGlobal;
constexpr size_t nBaseCaseSize = 1024;
const std::size_t nLen = static_cast<std::size_t>(aEnd - aBegin);
if (nLen < nBaseCaseSize)
{
std::stable_sort(aBegin, aEnd, aComp);
return;
}
using ValueType = typename std::iterator_traits<RandItr>::value_type;
auto pOut = std::make_unique<ValueType[]>(nLen);
const size_t nBins = lcl_round_down_pow2(nThreadCount);
const size_t nOverSamplingFactor = std::max(1.0, std::sqrt(static_cast<double>(nLen) / 64));
const size_t nSamples = nOverSamplingFactor * nBins;
auto aSamples = std::make_unique<ValueType[]>(nSamples);
ProfileZone aZoneSampleAnsSort("SampleAndSort");
// Select samples and sort them
Sampler<RandItr>::sample(aBegin, aEnd, aSamples.get(), nSamples, nBins);
std::sort(aSamples.get(), aSamples.get() + nSamples, aComp);
aZoneSampleAnsSort.stop();
if (!aComp(aSamples[0], aSamples[nSamples - 1]))
{
// All samples are equal, fallback to standard sort.
std::sort(aBegin, aEnd, aComp);
return;
}
ProfileZone aZoneBinner("Binner");
// Create and populate bins using pOut from input iterators.
Binner<RandItr, Compare> aBinner(aSamples.get(), nSamples, nBins, bThreaded);
aBinner.label(aBegin, aEnd, aComp);
aBinner.bin(aBegin, aEnd, pOut.get());
aZoneBinner.stop();
ProfileZone aZoneSortBins("SortBins");
ValueType* pOutRaw = pOut.get();
if (bThreaded)
{
ParallelRunner aPRunner;
// Sort the bins separately.
for (size_t nBinIdx = 0, nBinStart = 0; nBinIdx < nBins; ++nBinIdx)
{
size_t nBinEnd = aBinner.maBinEnds[nBinIdx];
aPRunner.enqueue([pOutRaw, nBinStart, nBinEnd, &aComp] {
std::sort(pOutRaw + nBinStart, pOutRaw + nBinEnd, aComp);
});
nBinStart = nBinEnd;
}
aPRunner.wait();
}
else
{
for (size_t nBinIdx = 0, nBinStart = 0; nBinIdx < nBins; ++nBinIdx)
{
auto nBinEnd = aBinner.maBinEnds[nBinIdx];
std::sort(pOutRaw + nBinStart, pOutRaw + nBinEnd, aComp);
nBinStart = nBinEnd;
}
}
aZoneSortBins.stop();
// Move the sorted array to the array specified by input iterators.
std::move(pOutRaw, pOutRaw + nLen, aBegin);
}
} // anonymous namespace
template <class RandItr, class Compare = std::less<>>
void parallelSort(const RandItr aBegin, const RandItr aEnd, Compare aComp = Compare())
{
assert(aBegin <= aEnd);
s3sort(aBegin, aEnd, aComp);
}
} // namespace comphelper
#endif // INCLUDED_COMPHELPER_PARALLELSORT_HXX
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */
|