aboutsummaryrefslogtreecommitdiff
path: root/src/main/java/dev/morling/onebrc/CalculateAverage_xpmatteo.java
blob: 94904ffb48bb01134f9328e3f88aafc6c9c96fb1 (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
/*
 *  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.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.TreeMap;
import java.util.stream.Collectors;

@SuppressWarnings({ "ReassignedVariable", "StatementWithEmptyBody" })
public class CalculateAverage_xpmatteo {

    private static final String FILE = "./measurements.txt";

    public static void main(String[] args) throws IOException, InterruptedException {
        var fileName = dataFileName(args);

        try (
                var file = new RandomAccessFile(new File(fileName), "r");
                var channel = file.getChannel()) {
            var numCpus = Runtime.getRuntime().availableProcessors();
            var threads = split(channel, numCpus).stream()
                    .map(Worker::new)
                    .toList();
            threads.forEach(Thread::start);
            for (Worker thread : threads) {
                thread.join();
            }
            var results = threads.stream().map(Worker::getResults)
                    .reduce(CalculateAverage_xpmatteo::merge)
                    .orElseThrow();
            printCities(results);
        }
    }

    public static class Worker extends Thread {
        private final ByteBuffer buffer;
        private Results results;

        public Worker(ByteBuffer buffer) {
            this.buffer = buffer;
        }

        @Override
        public void run() {
            this.results = parseData(this.buffer);
        }

        public Results getResults() {
            return results;
        }
    }

    protected static List<ByteBuffer> split(FileChannel channel, int numCpus) throws IOException {
        if (channel.size() < 10_000) {
            return List.of(channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size()));
        }

        long[] increments = new long[numCpus + 1];
        for (int i = 0; i < numCpus; i++) {
            increments[i] = i * channel.size() / numCpus;
            // adjust the increments so that they start on the beginning of a city
            while (increments[i] > 0 && byteAt(channel, increments[i] - 1) != '\n') {
                increments[i]--;
            }
        }
        increments[numCpus] = channel.size();

        List<ByteBuffer> result = new ArrayList<>(numCpus);
        for (int i = 0; i < numCpus; i++) {
            long from = increments[i];
            long to = increments[i + 1];
            result.add(channel.map(FileChannel.MapMode.READ_ONLY, from, to - from));
        }
        return result;
    }

    private static byte byteAt(FileChannel channel, long offset) throws IOException {
        ByteBuffer buf = ByteBuffer.allocate(1);
        channel.position(offset);
        channel.read(buf);
        buf.flip();
        var bytes = new byte[1];
        buf.get(bytes);
        return bytes[0];
    }

    public static String dataFileName(String[] args) {
        if (args.length == 1) {
            return args[0];
        }
        return FILE;
    }

    protected static byte[] readAllData(String fileName) throws IOException {
        return Files.readAllBytes(Path.of(fileName));
    }

    protected static ByteBuffer memoryMap(String fileName) throws IOException {
        try (RandomAccessFile file = new RandomAccessFile(new File(fileName), "r")) {
            // Get file channel in read-only mode
            FileChannel fileChannel = file.getChannel();

            return fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileChannel.size());
        }
    }

    protected enum State {
        PARSING_CITY_NAME,
        SKIPPING_SEMICOLON,
        PARSING_TEMPERATURE
    }

    protected static Results parseData(ByteBuffer data) {
        var results = new Results();
        var state = State.PARSING_CITY_NAME;
        int cityStartOffset = 0, cityEndOffset = 0;
        int temp = 0, sign = 0;

        for (int i = 0; i < data.limit(); i++) {
            byte currentChar = data.get();
            if (state == State.PARSING_CITY_NAME && currentChar == ';') {
                state = State.SKIPPING_SEMICOLON;
                cityEndOffset = i;
            }
            else if (state == State.PARSING_CITY_NAME) {
                // do nothing
            }
            else if (state == State.SKIPPING_SEMICOLON && currentChar == '-') {
                state = State.PARSING_TEMPERATURE;
                temp = 0;
                sign = -1;
            }
            else if (state == State.SKIPPING_SEMICOLON && currentChar >= '0' && currentChar <= '9') {
                state = State.PARSING_TEMPERATURE;
                temp = currentChar - '0';
                sign = 1;
            }
            else if (state == State.PARSING_TEMPERATURE && currentChar >= '0' && currentChar <= '9') {
                temp = temp * 10 + currentChar - '0';
            }
            else if (state == State.PARSING_TEMPERATURE && currentChar == '.') {
                // do nothing
            }
            else if (state == State.PARSING_TEMPERATURE && currentChar == '\n') {
                byte[] bytes = new byte[cityEndOffset - cityStartOffset];
                data.get(cityStartOffset, bytes);
                var cityName = new String(bytes);
                accumulate(results, cityName, temp * sign);
                state = State.PARSING_CITY_NAME;
                cityStartOffset = i + 1;
            }
        }

        return results;
    }

    private static void accumulate(Results results, String cityName, int tempTimesTen) {
        var existing = results.get(cityName);
        if (existing == null) {
            results.put(cityName, new CityData(tempTimesTen, tempTimesTen, tempTimesTen, 1));
        }
        else {
            existing.min = Math.min(existing.min, tempTimesTen);
            existing.sum = existing.sum + tempTimesTen;
            existing.max = Math.max(existing.max, tempTimesTen);
            existing.count++;
        }
    }

    protected static Results merge(Results a, Results b) {
        for (var entry : b.entrySet()) {
            CityData valueInA = a.get(entry.getKey());
            if (null == valueInA) {
                a.put(entry.getKey(), entry.getValue());
            }
            else {
                var valueInB = entry.getValue();
                valueInA.min = Math.min(valueInA.min, valueInB.min);
                valueInA.sum += valueInB.sum;
                valueInA.max = Math.max(valueInA.max, valueInB.max);
                valueInA.count += valueInB.count;
            }
        }

        return a;
    }

    protected static class Results extends TreeMap<String, CityData> {

    }

    protected static class CityData {
        int min, sum, max, count;

        public CityData(int min, int sum, int max, int count) {
            this.min = min;
            this.sum = sum;
            this.max = max;
            this.count = count;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o)
                return true;
            if (o == null || getClass() != o.getClass())
                return false;
            CityData cityData = (CityData) o;
            return min == cityData.min && sum == cityData.sum && max == cityData.max && count == cityData.count;
        }

        @Override
        public int hashCode() {
            return Objects.hash(min, sum, max, count);
        }

        @Override
        public String toString() {
            return STR."CityData{min=\{min}, sum=\{sum}, max=\{max}, count=\{count}\{'}'}";
        }
    }

    protected static void printCities(Results cities) {
        System.out.print("{");
        for (String city : cities.keySet()) {
            CityData data = cities.get(city);
            var min = data.min / 10.0;
            var mean = (data.sum * 10.0 / data.count) / 100.0;
            var max = data.max / 10.0;
            System.out.printf(
                    "%s=%.1f/%.1f/%.1f, ",
                    city,
                    min,
                    mean,
                    max);
        }
        System.out.print("}");
    }
}