-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
CalculateAverage_Judekeyser.java
414 lines (376 loc) · 16.3 KB
/
CalculateAverage_Judekeyser.java
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
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/*
* Copyright 2023 The original authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package dev.morling.onebrc;
import jdk.incubator.vector.ByteVector;
import jdk.incubator.vector.VectorSpecies;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.io.UncheckedIOException;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.nio.ByteOrder;
import java.nio.channels.FileChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Paths;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import static java.lang.foreign.ValueLayout.OfByte.JAVA_BYTE;
import static java.lang.foreign.ValueLayout.OfByte.JAVA_INT_UNALIGNED;
public class CalculateAverage_Judekeyser {
private static final String FILE = "./measurements.txt";
private static final int chunkSize = (1 << 7) << 12; // This can't go beyond 2^21, because otherwise we might exceed int capacity
private static final int numberOfIOWorkers = 1 << 8; // We are going to need (numberOfIOWorkers-1) * chunkSize capacity
private static final int numberOfParallelWorkers = Runtime.getRuntime().availableProcessors() - 1;
private static final VectorSpecies<Byte> SPECIES = ByteVector.SPECIES_PREFERRED;
public static void main(String[] args) throws Exception {
class SimpleStatistics {
int min, max, sum, count;
SimpleStatistics() {
min = Integer.MAX_VALUE;
max = Integer.MIN_VALUE;
sum = 0;
count = 0;
}
void accept(int value) {
min = Math.min(min, value);
max = Math.max(max, value);
sum += value;
count++;
}
}
class Statistics {
double min, max, avg;
long count;
Statistics(SimpleStatistics simple) {
min = simple.min/10.;
max = simple.max/10.;
avg = simple.sum/10./simple.count;
count = simple.count;
}
void accept(SimpleStatistics simple) {
min = Math.min(min, simple.min/10.);
max = Math.max(max, simple.max/10.);
var nextCount = count + simple.count;
avg = (avg * count + simple.sum/10.)/nextCount;
count = nextCount;
}
static final DecimalFormat format;
static {
var decimalFormatSymbols = DecimalFormatSymbols.getInstance();
decimalFormatSymbols.setDecimalSeparator('.');
format = new DecimalFormat("#0.0", decimalFormatSymbols);
}
@Override
public String toString() {
return STR."\{format.format(round(min))}/\{format.format(round(avg))}/\{format.format(round(max))}";
}
static double round(double d) {
return Math.round(d*10.)/10.;
}
}
class Name {
final int[] data;
final int hash;
Name(int[] data) {
this.data = data;
{
var hash = 0;
for (var d : data) {
hash = 31 * hash + d;
}
this.hash = hash;
}
}
@Override
public int hashCode() {
return hash;
}
@Override
public boolean equals(Object obj) {
if(obj == this) return true;
else if(obj instanceof Name name && name.data.length == data.length) {
int size = 0;
while(size < data.length) {
if(data[size] != name.data[size]) {
return false;
} else size++;
}
return true;
} else return false;
}
@Override
public String toString() {
var bdata = new byte[data.length * 4];
int j = 0;
for(int i = 0;i < data.length; i++) {
bdata[j++] = (byte)((data[i] >>> 0) & 255);
bdata[j++] = (byte)((data[i] >>> 8) & 255);
bdata[j++] = (byte)((data[i] >>> 16) & 255);
bdata[j++] = (byte)((data[i] >>> 24) & 255);
}
while(bdata[--j] == 0);
return new String(bdata, 0, j+1, StandardCharsets.UTF_8);
}
}
record Line(Name name, int value) {}
var results = new HashMap<Name, Statistics>();
try(var file = new RandomAccessFile(Paths.get(FILE).toFile(), "r")) {
class Ls implements Iterator<MemorySegment> {
final int M = chunkSize;
final Arena arena = Arena.ofShared();
final long length;
long offset;
Ls() throws IOException {
offset = 0L;
length = file.length();
}
@Override
public MemorySegment next() {
MemorySegment memorySegment;
try {
memorySegment = file.getChannel().map(
FileChannel.MapMode.READ_ONLY,
offset, Math.min(M + 128L, file.getChannel().size() - offset),
arena
);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
var size = M;
if (offset + M < length) {
b:
{
for (int N = 0; N < 128; N++) {
var b = memorySegment.get(JAVA_BYTE, size);
size += 1;
if (b == '\n') {
break b;
}
}
assert false : "Lines are smaller than 128 bytes";
}
offset += size;
} else {
size = (int) (length - offset);
offset = length;
}
return memorySegment.asSlice(0, size);
}
@Override
public boolean hasNext() {
return offset < length;
}
}
class It implements Iterator<Line> {
int offset;
final int length;
final MemorySegment memorySegment;
final ByteOrder endian;
It(MemorySegment memorySegment) {
offset = 0;
endian = ByteOrder.nativeOrder();
this.memorySegment = memorySegment;
length = (int) memorySegment.byteSize();
assert '\n' == memorySegment.get(JAVA_BYTE, length - 1);
}
@Override
public boolean hasNext() {
return offset < length;
}
@Override
public Line next() {
int size;
b: {
/*
* Vectorization does not seem to bring anything interesting.
* This is a bit disappointing. What am I doing wrong?
*/
size = 0;
while (offset+size+SPECIES.length() <= length) {
var vector = ByteVector.fromMemorySegment(
SPECIES, memorySegment,
offset+size, endian
);
var j = vector.eq((byte) '\n').firstTrue();
if (j < SPECIES.length()) {
assert j >= 0;
size += j;
assert memorySegment.get(JAVA_BYTE, offset+size) == '\n';
break b;
} else {
assert j == SPECIES.length();
size += SPECIES.length();
}
}
{
byte b;
for (; size < 128; size++) {
b = memorySegment.get(JAVA_BYTE, offset+size);
if (b == '\n') break b;
}
assert false : "Lines are smaller than 128 bytes";
}
assert memorySegment.get(JAVA_BYTE, offset+size) == '\n';
assert size < 128;
}
Name name;
int value;
{
long cursor = offset+size - 1L;
{
value = memorySegment.get(JAVA_BYTE, cursor) - '0';
value += (memorySegment.get(JAVA_BYTE, cursor-2L) - '0') * 10;
cursor -= 3L;
if (memorySegment.get(JAVA_BYTE, cursor) == '-') {
value *= -1;
cursor -= 1L;
} else if (memorySegment.get(JAVA_BYTE, cursor) != ';') {
value += (memorySegment.get(JAVA_BYTE, cursor) - '0') * 100;
cursor -= 1L;
if (memorySegment.get(JAVA_BYTE, cursor) == '-') {
value *= -1;
cursor -= 1L;
}
}
}
//var data = memorySegment.asSlice(offset, cursor-offset).toArray(JAVA_BYTE);
//System.arraycopy(chunk, 0, data, 0, data.length);
//assert ';' != data[data.length - 1];
//name = new Name(data);
{
int mod4StringSize = ((int)(cursor-offset+3))/4 * 4;
var data = memorySegment.asSlice(offset, mod4StringSize).toArray(JAVA_INT_UNALIGNED);
switch(((int)(cursor - offset)) % 4) {
case 0: break;
case 1: {
data[data.length - 1] &= 255;
} break;
case 2: {
data[data.length - 1] &= 65535;
} break;
case 3: {
data[data.length - 1] &= 16777215;
} break;
}
name = new Name(data);
}
}
offset += size + 1;
return new Line(name, value);
}
}
record Pair(MemorySegment segment, Map<Name, SimpleStatistics> simple) {
Pair(MemorySegment segment) {
this(segment, apply(segment));
}
private static Map<Name, SimpleStatistics> apply(MemorySegment memorySegment) {
try {
return call(memorySegment);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
private static Map<Name, SimpleStatistics> call(MemorySegment memorySegment) throws IOException {
var it = new It(memorySegment);
var simple = new HashMap<Name, SimpleStatistics>();
while (it.hasNext()) {
var line = it.next();
var name = line.name();
var value = line.value();
var statistics = simple.get(name);
if (statistics == null) {
statistics = new SimpleStatistics();
simple.put(name, statistics);
}
statistics.accept(value);
}
return simple;
}
}
var ls = new Ls();
try(
var nioService = Executors.newVirtualThreadPerTaskExecutor();
var parallelService =Executors.newFixedThreadPool(numberOfParallelWorkers)
) {
var tasksQueue = new ArrayList<Future<Pair>>();
for(;;) {
assert tasksQueue.size() <= numberOfIOWorkers;
if(tasksQueue.size() < numberOfIOWorkers) {
if(ls.hasNext()) {
var memseg = ls.next();
var task = CompletableFuture.supplyAsync(
() -> {
memseg.load();
return memseg;
}, nioService
).thenApplyAsync(Pair::new, parallelService);
tasksQueue.add(task);
} else if(tasksQueue.isEmpty()) break;
}
/*
* Wait for the tasks and merge what's ready
*/
{
var copy = new ArrayList<Future<Pair>>(tasksQueue.size());
for(var worker: tasksQueue) {
if(worker.isDone()) {
/*
* Merge the maps
*/
var p = worker.get();
var simple = p.simple();
p.segment().unload();
for (var entry : simple.entrySet()) {
var name = entry.getKey();
var statistics = results.get(name);
if (statistics == null) {
statistics = new Statistics(entry.getValue());
results.put(name, statistics);
} else {
statistics.accept(entry.getValue());
}
}
} else copy.add(worker);
}
tasksQueue.clear();
tasksQueue.addAll(copy);
}
}
}
}
/*
* Print
*/
{
var sortedMap = new TreeMap<String, Statistics>();
for(var entry: results.entrySet()) {
sortedMap.put(
entry.getKey().toString(),
entry.getValue()
);
}
var joiner = new StringJoiner(", ", "{", "}");
for (var entry : sortedMap.entrySet()) {
joiner.add(STR. "\{ entry.getKey() }=\{ entry.getValue() }" );
}
System.out.println(joiner);
}
}
}