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
|
/*
* 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 sun.misc.Unsafe;
import java.io.RandomAccessFile;
import java.lang.foreign.Arena;
import java.lang.foreign.MemorySegment;
import java.lang.reflect.Field;
import java.nio.channels.FileChannel;
import java.util.Map;
import java.util.TreeMap;
public final class CalculateAverage_JaimePolidura {
private static final String FILE = "./measurements.txt";
private static final Unsafe UNSAFE = initUnsafe();
private static final long SEMICOLON_PATTERN = 0X3B3B3B3B3B3B3B3BL;
private static Unsafe initUnsafe() {
try {
Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
theUnsafe.setAccessible(true);
return (Unsafe) theUnsafe.get(Unsafe.class);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) throws Exception {
Worker[] workers = createWorkers();
startWorkers(workers);
joinWorkers(workers);
Map<String, Result> results = mergeWorkersResults(workers);
printResults(results);
}
private static void joinWorkers(Worker[] workers) throws InterruptedException {
for (int i = 0; i < workers.length; i++) {
workers[i].join();
}
}
private static void startWorkers(Worker[] workers) {
for (int i = 0; i < workers.length; i++) {
workers[i].start();
}
}
private static Worker[] createWorkers() throws Exception {
FileChannel channel = new RandomAccessFile(FILE, "r").getChannel();
MemorySegment mmappedFile = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size(), Arena.global());
int nWorkers = channel.size() > 1024 * 1024 ? Runtime.getRuntime().availableProcessors() : 1;
Worker[] workers = new Worker[nWorkers];
long quantityPerWorker = Math.floorDiv(channel.size(), nWorkers);
long quantityLastWorker = quantityPerWorker + (channel.size() % nWorkers);
for (int i = 0; i < nWorkers; i++) {
boolean isLastWorker = i == nWorkers - 1;
long startAddr = mmappedFile.address() + quantityPerWorker * i;
long endAddr = startAddr + (isLastWorker ? quantityLastWorker : quantityPerWorker);
workers[i] = new Worker(mmappedFile, channel.size(), startAddr, endAddr);
workers[i].setPriority(Thread.MAX_PRIORITY);
}
return workers;
}
private static Map<String, Result> mergeWorkersResults(Worker[] workers) {
Map<String, Result> mergedResults = new TreeMap<>();
for (int i = 0; i < workers.length; i++) {
Worker worker = workers[i];
for (Result entry : worker.results.entries) {
if (entry != null) {
String name = new String(entry.name, 0, entry.nameLength);
Result alreadyExistingResult = mergedResults.get(name);
if (alreadyExistingResult != null) {
alreadyExistingResult.min = Math.min(alreadyExistingResult.min, entry.min);
alreadyExistingResult.max = Math.max(alreadyExistingResult.max, entry.max);
alreadyExistingResult.count = alreadyExistingResult.count + entry.count;
alreadyExistingResult.sum = alreadyExistingResult.sum + entry.sum;
}
else {
mergedResults.put(name, entry);
}
}
}
}
return mergedResults;
}
private static void printResults(Map<String, Result> results) {
StringBuilder stringBuilder = new StringBuilder(results.size() * 32);
stringBuilder.append('{');
for (Map.Entry<String, Result> entry : results.entrySet()) {
if (stringBuilder.length() > 1) {
stringBuilder.append(", ");
}
Result result = entry.getValue();
stringBuilder.append(entry.getKey())
.append('=')
.append(round(((double) result.min) / 10.0))
.append('/')
.append(round((double) result.sum / (result.count * 10)))
.append('/')
.append(round(((double) result.max) / 10.0d));
}
stringBuilder.append('}');
System.out.println(stringBuilder);
}
static class Worker extends Thread {
private final byte[] lastParsedNameBytes = new byte[100];
private int lastParsedNameLength;
private long lastParsedNameHash;
private int lastParsedTemperature;
private final SimpleMap results;
private final MemorySegment mmappedFile;
private final long mmappedFileSize;
private long currentAddr; // Will point to beginning of string
private long endAddr; // Will point to \n
public Worker(MemorySegment mmappedFile, long mmappedFileSize, long startAddr, long endAddr) {
super("Worker[" + startAddr + ", " + endAddr + "]");
this.mmappedFileSize = mmappedFileSize;
this.mmappedFile = mmappedFile;
this.currentAddr = startAddr;
this.endAddr = endAddr;
this.results = new SimpleMap(roundUpToPowerOfTwo(1 << 16)); // 2^16
}
@Override
public void run() {
adjustStartAddr();
adjustEndAddr();
if (this.currentAddr >= endAddr) {
return;
}
while (currentAddr < endAddr) {
parseName();
parseTemperature();
this.currentAddr++; // We don't want it to point to \n
results.put(this.lastParsedNameHash, this.lastParsedNameBytes, this.lastParsedNameLength, this.lastParsedTemperature);
}
}
// Idea from Quan Anh Mai's implementation
private void parseTemperature() {
long numberWord = UNSAFE.getLong(currentAddr);
// The 4th binary digit of the ascii (Starting from left) of a digit is 1 while '.' is 0
int decimalSepPos = Long.numberOfTrailingZeros(~numberWord & 0x10101000);
// 28 = 4 + 8 * 3 (4 bytes is the number of tail zeros in the byte of decimalPos)
// xxxn.nn- shift: 28 - 28 = 0
// xxxxxn.n shift: 28 - 12 = 16
// xxxxn.nn shift: 28 - 20 = 8
int shift = 28 - decimalSepPos;
// Negative in ASCII: 00101101 2D. In ascii every digit starts with hex digit 3
// So in order to know if a number is positive, we simpy need the first bit of the 2º half
// If signed is 0 the number is positive. If it is negative signed will be -1.
long signed = (~numberWord << 59) >> 63;
// If signed is 0 (positive), designMask will be 0xFFFFFFFFFFFFFFFF (-256)
// If signed is -1, all 1s (negative), designMask will be 0xFFFFFFFFFFFFFF00 (-1)
long designMask = ~(signed & 0xFF);
// Align the number to a fixed position
// (x represents any non-related character, _ represents 0x00, n represents the actual digit and - negative)
// xxxn.nn- -> xxxn.nn-
// xxxxxn.n -> xxxn.n__
// xxxxn.nn -> xxxn.nn_
long numberAligned = (numberWord & designMask) << shift;
// We convert ascii representation to number value
long numberConvertedFromAscii = numberAligned & 0x0F000F0F00L;
// Now digits is in the form 0xUU00TTHH00 (UU: units digit, TT: tens digit, HH: hundreds digit)
// 0xUU00TTHH00 * (100 * 0x1000000 + 10 * 0x10000 + 1) =
// 0x000000UU00TTHH00 +
// 0x00UU00TTHH000000 * 10 +
// 0xUU00TTHH00000000 * 100
// Now TT * 100 has 2 trailing zeroes and HH * 100 + TT * 10 + UU < 0x400
// This results in our value lies in the bit 32 to 41 of this product
// That was close :)
long absValue = ((numberConvertedFromAscii * 0x640a0001) >>> 32) & 0x3FF;
long signedValue = (absValue ^ signed) - signed;
this.currentAddr += (((decimalSepPos - 4) / 8) + 2);
this.lastParsedTemperature = (int) signedValue;
}
// I first saw this idea in Artsiom Korzun's implementation
private void parseName() {
this.lastParsedNameHash = 0;
long totalWordHash = 0;
int totalWordLength = 0;
for (;;) {
long actualWord = UNSAFE.getLong(currentAddr + totalWordLength);
long hasSemicolon = hasByte(actualWord, SEMICOLON_PATTERN);
if (hasSemicolon != 0) {
int actualLength = Long.numberOfTrailingZeros(hasSemicolon) >> 3;
if (actualLength == 0) {
actualWord = 0;
}
actualWord = mask(actualWord, actualLength);
UNSAFE.putLong(this.lastParsedNameBytes, Unsafe.ARRAY_BYTE_BASE_OFFSET + totalWordLength, actualWord);
totalWordHash ^= actualWord;
totalWordLength += actualLength;
this.lastParsedNameLength = totalWordLength;
this.lastParsedNameHash = totalWordHash;
this.currentAddr += totalWordLength + 1; // +1 Because we don't want to point to ';'
break;
}
else {
UNSAFE.putLong(this.lastParsedNameBytes, Unsafe.ARRAY_BYTE_BASE_OFFSET + totalWordLength, actualWord);
totalWordLength += 8;
totalWordHash ^= actualWord;
}
}
}
// Removes "garbage" of a word byte
private long mask(long word, int length) {
int shift = (8 - length) * 8;
return (word << shift) >> shift;
}
private long hasByte(long word, long pattern) {
long patternMatch = word ^ pattern;
return (patternMatch - 0x0101010101010101L) & (~patternMatch & 0x8080808080808080L);
}
private void adjustStartAddr() {
if (currentAddr == this.mmappedFile.address()) {
return;
}
while (UNSAFE.getByte(currentAddr) != '\n' && currentAddr != endAddr) {
currentAddr++;
}
currentAddr++; // We want it to point to the first character instead of \n
}
private void adjustEndAddr() {
long endAddressMmappedFile = mmappedFile.address() + mmappedFileSize;
if (endAddr >= endAddressMmappedFile) {
return;
}
while (UNSAFE.getByte(endAddr) != '\n' && endAddr != endAddressMmappedFile) {
endAddr++;
}
}
}
static class SimpleMap {
private final Result[] entries;
private final long size;
public SimpleMap(int size) {
this.entries = new Result[size];
this.size = size;
}
public void put(long hashToPut, byte[] nameToPut, int nameLength, int valueToPut) {
int index = toIndex(hashToPut);
for (;;) {
Result actualEntry = entries[index];
if (actualEntry == null) {
byte[] nameToPutCopy = new byte[nameLength];
UNSAFE.copyMemory(nameToPut, Unsafe.ARRAY_BYTE_BASE_OFFSET, nameToPutCopy, Unsafe.ARRAY_BYTE_BASE_OFFSET, nameLength);
entries[index] = new Result(hashToPut, nameToPutCopy, nameLength, valueToPut,
valueToPut, valueToPut, 1);
return;
}
if (actualEntry.isSameName(nameToPut, nameLength)) {
actualEntry.min = Math.min(actualEntry.min, valueToPut);
actualEntry.max = Math.max(actualEntry.max, valueToPut);
actualEntry.count++;
actualEntry.sum = actualEntry.sum + valueToPut;
return;
}
index = toIndex(index + 31);
}
}
private int toIndex(long hash) {
return (int) (((hash >> 32) ^ ((int) hash)) & (this.size - 1));
}
}
static class Result {
public byte[] name;
public int nameLength;
public int max;
public int min;
public int sum;
public int count;
public long hash;
public Result(long hash, byte[] name, int nameLength, int max, int min, int sum, int occ) {
this.nameLength = nameLength;
this.count = occ;
this.hash = hash;
this.name = name;
this.max = max;
this.min = min;
this.sum = sum;
}
public boolean isSameName(byte[] otherNameBytes, int otherNameLength) {
return this.nameLength == otherNameLength && isSameNameBytes(otherNameBytes);
}
private boolean isSameNameBytes(byte[] otherNameBytes) {
for (int i = 0; i < this.nameLength; i += 8) {
long thisNameBytesAsLong = UNSAFE.getLong(this.name, Unsafe.ARRAY_BYTE_BASE_OFFSET + i);
long otherNameBytesAsLong = UNSAFE.getLong(otherNameBytes, Unsafe.ARRAY_BYTE_BASE_OFFSET + i);
int isPositiveAsInt = (((8 - nameLength + i) >> 31) & 1) ^ 0x01;
int shift = ((8 - nameLength + i) * isPositiveAsInt) * 8;
otherNameBytesAsLong = (otherNameBytesAsLong << shift) >>> shift;
if (thisNameBytesAsLong != otherNameBytesAsLong) {
return false;
}
}
return true;
}
}
private static double round(double value) {
return Math.round(value * 10.0) / 10.0;
}
private static int roundUpToPowerOfTwo(int number) {
if (number <= 0) {
return 1;
}
number--;
number |= number >> 1;
number |= number >> 2;
number |= number >> 4;
number |= number >> 8;
number |= number >> 16;
return number + 1;
}
}
|