aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/dev/morling/onebrc/CalculateAverage_plbpietrz.java
blob: 9fb382582ac001af64d1a734af94ed12334e4e28 (plain)
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
/*
 *  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 java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.RandomAccessFile;
import java.io.UncheckedIOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class CalculateAverage_plbpietrz {

    private static final String FILE = "./measurements.txt";
    private static final int READ_SIZE = 1024;
    private static final int CPU_COUNT = Runtime.getRuntime().availableProcessors();

    private static class TemperatureStats {
        double min = 999, max = -999d;
        double accumulated;
        int count;

        public void update(double temp) {
            this.min = Math.min(this.min, temp);
            this.max = Math.max(this.max, temp);
            this.accumulated += temp;
            this.count++;
        }
    }

    private record FilePart(long pos, long size) {
    }

    private static class WeatherStation {
        private int length;
        private int nameHash;
        private byte[] nameBytes;
        private String string;

        public WeatherStation() {
            nameBytes = new byte[128];
        }

        public WeatherStation(WeatherStation station) {
            this.nameBytes = Arrays.copyOf(station.nameBytes, station.length);
            this.length = station.length;
            this.nameHash = station.nameHash;
        }

        @Override
        public int hashCode() {
            return nameHash;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o instanceof WeatherStation s) {
                return this.nameHash == s.nameHash && Arrays.equals(this.nameBytes, 0, this.length, s.nameBytes, 0, s.length);
            }
            return false;
        }

        @Override
        public String toString() {
            if (string == null)
                string = new String(nameBytes, 0, length, Charset.defaultCharset());
            return string;
        }

        public void appendByte(byte b) {
            string = null;
            nameBytes[length++] = b;
            nameHash = nameHash * 31 + b;
        }

        public void clear() {
            this.length = 0;
            this.nameHash = 0;
            this.string = null;
        }

    }

    public static void main(String[] args) throws IOException {
        Path inputFilePath = Path.of(FILE);
        Map<WeatherStation, TemperatureStats> results;
        try (RandomAccessFile inputFile = new RandomAccessFile(inputFilePath.toFile(), "r")) {
            var parsedBuffers = partitionInput(inputFile)
                    .stream()
                    .parallel()
                    .map(fp -> getMappedByteBuffer(fp, inputFile))
                    .map(CalculateAverage_plbpietrz::parseBuffer);
            results = parsedBuffers.flatMap(m -> m.entrySet().stream())
                    .collect(
                            Collectors.groupingBy(
                                    Map.Entry::getKey,
                                    Collectors.reducing(
                                            new TemperatureStats(),
                                            Map.Entry::getValue,
                                            CalculateAverage_plbpietrz::mergeTemperatureStats)));
            try (PrintWriter pw = new PrintWriter(new BufferedOutputStream(System.out))) {
                formatResults(pw, results);
            }
        }
    }

    private static List<FilePart> partitionInput(RandomAccessFile inputFile) throws IOException {
        List<FilePart> fileParts = new ArrayList<>();
        long fileLength = inputFile.length();

        long blockSize = Math.min(fileLength, Math.max(READ_SIZE, fileLength / CPU_COUNT));

        for (long start = 0, end; start < fileLength; start = end) {
            end = findMinBlockOffset(inputFile, start, blockSize);
            fileParts.add(new FilePart(start, end - start));
        }
        return fileParts;
    }

    private static long findMinBlockOffset(RandomAccessFile file, long startPosition, long minBlockSize) throws IOException {
        long length = file.length();
        if (startPosition + minBlockSize < length) {
            file.seek(startPosition + minBlockSize);
            while (file.readByte() != '\n') {
            }
            return file.getFilePointer();
        }
        else {
            return length;
        }
    }

    private static MappedByteBuffer getMappedByteBuffer(FilePart fp, RandomAccessFile inputFile) {
        try {
            return inputFile.getChannel().map(FileChannel.MapMode.READ_ONLY, fp.pos, fp.size);
        }
        catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    }

    private static Map<WeatherStation, TemperatureStats> parseBuffer(MappedByteBuffer buffer) {
        byte[] readLong = new byte[READ_SIZE];
        byte[] temperature = new byte[32];
        int temperatureLineLenght = 0;

        int limit = buffer.limit();
        boolean readingName = true;
        Map<WeatherStation, TemperatureStats> temperatures = new HashMap<>();
        WeatherStation station = new WeatherStation();

        int bytesToRead = Math.min(READ_SIZE, limit - buffer.position());
        while (bytesToRead > 0) {
            if (bytesToRead == READ_SIZE) {
                buffer.get(readLong);
            }
            else {
                for (int j = 0; j < bytesToRead; ++j)
                    readLong[j] = buffer.get();
            }

            for (int i = 0; i < bytesToRead; ++i) {
                byte aChar = readLong[i];
                if (readingName) {
                    if (aChar != ';') {
                        if (aChar != '\n') {
                            station.appendByte(aChar);
                        }
                    }
                    else {
                        readingName = false;
                    }
                }
                else {
                    if (aChar != '\n') {
                        temperature[temperatureLineLenght++] = aChar;
                    }
                    else {
                        double temp = parseTemperature(temperature, temperatureLineLenght);

                        if (!temperatures.containsKey(station)) {
                            temperatures.put(new WeatherStation(station), new TemperatureStats());
                        }
                        TemperatureStats weatherStats = temperatures.get(station);
                        weatherStats.update(temp);

                        station.clear();
                        temperatureLineLenght = 0;
                        readingName = true;
                    }
                }
            }

            bytesToRead = Math.min(READ_SIZE, limit - buffer.position());
        }
        return temperatures;
    }

    private static double parseTemperature(byte[] temperature, int temperatureSize) {
        double sign = 1;
        double manitssa = 0;
        double exponent = 1;
        for (int i = 0; i < temperatureSize; ++i) {
            byte c = temperature[i];
            switch (c) {
                case '-':
                    sign = -1;
                    break;
                case '.':
                    for (int j = i; j < temperatureSize - 1; ++j)
                        exponent *= 0.1;
                    break;
                default:
                    manitssa = manitssa * 10 + (c - 48);
            }
        }
        return sign * manitssa * exponent;
    }

    private static TemperatureStats mergeTemperatureStats(TemperatureStats v1, TemperatureStats v2) {
        TemperatureStats acc = new TemperatureStats();
        acc.min = Math.min(v1.min, v2.min);
        acc.max = Math.max(v1.max, v2.max);
        acc.accumulated = v1.accumulated + v2.accumulated;
        acc.count = v1.count + v2.count;
        return acc;
    }

    private static void formatResults(PrintWriter pw, Map<WeatherStation, TemperatureStats> resultsMap) {
        pw.print('{');
        var results = new ArrayList<>(resultsMap.entrySet());
        results.sort(Comparator.comparing(e -> e.getKey().toString()));
        var iterator = results.iterator();
        while (iterator.hasNext()) {
            var entry = iterator.next();
            TemperatureStats stats = entry.getValue();
            pw.printf("%s=%.1f/%.1f/%.1f",
                    entry.getKey(),
                    stats.min,
                    stats.accumulated / stats.count,
                    stats.max);
            if ((iterator.hasNext()))
                pw.print(", ");
        }
        pw.println('}');
    }

}