/
go_parallel_II.go
291 lines (255 loc) · 7.57 KB
/
go_parallel_II.go
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
// SPDX-FileCopyrightText: Copyright 2024 Roland Csaszar
// SPDX-License-Identifier: MIT
//
// Project: 1-billion-row-challenge
// File: go_parallel_II.go
// Date: 06.Mar.2024
//
// =============================================================================
package main
import (
"bytes"
"fmt"
"math"
"os"
"runtime"
"sort"
)
type stationTemperatures struct {
TempSum []int
Count []uint
Min []int
Max []int
}
type chunk struct {
StartIdx int64
EndIdx int64
}
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "Error: no data file to process given! Exiting.")
os.Exit(1)
}
numCPUs := 20 * runtime.NumCPU()
fileName := os.Args[1]
file, err := os.Open(fileName)
if err != nil {
fmt.Fprintf(os.Stderr, "Error opening file '%s':\n%s\n", fileName, err)
os.Exit(2)
}
defer file.Close()
fsInfo, err := file.Stat()
if err != nil {
fmt.Fprintf(os.Stderr, "Error getting data of file '%s':\n%s\n", fileName, err)
os.Exit(3)
}
size := fsInfo.Size()
chunkSize := size / int64(numCPUs)
chunkList := generateChunkIndices(numCPUs, size, chunkSize, err, file, fileName)
channels := make([]chan resultType, numCPUs)
for idx, chunk := range chunkList {
// blocking channels
channels[idx] = make(chan resultType)
go processChunk(chunk, file, channels[idx])
}
numSumChans := 2
numToSum := numCPUs / numSumChans
sumChannels := make([]chan resultType, numSumChans)
for i := 0; i < numSumChans; i++ {
// blocking channels
sumChannels[i] = make(chan resultType)
go sumResults(channels[i*numToSum:(i+1)*numToSum], sumChannels[i])
}
stationSumData := stationTemperatures{
TempSum: make([]int, 10_000),
Count: make([]uint, 10_000),
Min: make([]int, 10_000),
Max: make([]int, 10_000),
}
stationSumIdxMap := make(map[string]int, 10_000)
stationIdx := 0
for _, channel := range sumChannels {
result := <-channel
stationData := result.Temps
stationIdxMap := result.IdxMap
for station, idx := range stationIdxMap {
stIdx, ok := stationSumIdxMap[station]
if ok {
stationSumData.TempSum[stIdx] += stationData.TempSum[idx]
stationSumData.Count[stIdx] += stationData.Count[idx]
stationSumData.Min[stIdx] = min(stationData.Min[idx], stationSumData.Min[stIdx])
stationSumData.Max[stIdx] = max(stationData.Max[idx], stationSumData.Max[stIdx])
} else {
stationSumIdxMap[station] = stationIdx
stationSumData.TempSum[stationIdx] = stationData.TempSum[idx]
stationSumData.Count[stationIdx] = stationData.Count[idx]
stationSumData.Min[stationIdx] = stationData.Min[idx]
stationSumData.Max[stationIdx] = stationData.Max[idx]
stationIdx++
}
}
}
keys := make([]string, 0, 10_000)
for key := range stationSumIdxMap {
keys = append(keys, key)
}
sort.Strings(keys)
fmt.Printf("{")
for i, station := range keys {
if i > 0 {
fmt.Printf(", ")
}
idx := stationSumIdxMap[station]
meanF := float64(stationSumData.TempSum[idx]) / float64(stationSumData.Count[idx])
fmt.Printf("%s=%.1f/%.1f/%.1f", station,
roundJava(float64(stationSumData.Min[idx])),
roundJava(meanF),
roundJava(float64(stationSumData.Max[idx])))
}
fmt.Printf("}\n")
}
func sumResults(channels []chan resultType, result chan resultType) {
stationSumData := stationTemperatures{
TempSum: make([]int, 10_000),
Count: make([]uint, 10_000),
Min: make([]int, 10_000),
Max: make([]int, 10_000),
}
stationSumIdxMap := make(map[string]int, 10_000)
stationIdx := 0
for _, channel := range channels {
result := <-channel
stationData := result.Temps
stationIdxMap := result.IdxMap
for station, idx := range stationIdxMap {
stIdx, ok := stationSumIdxMap[station]
if ok {
stationSumData.TempSum[stIdx] += stationData.TempSum[idx]
stationSumData.Count[stIdx] += stationData.Count[idx]
stationSumData.Min[stIdx] = min(stationData.Min[idx], stationSumData.Min[stIdx])
stationSumData.Max[stIdx] = max(stationData.Max[idx], stationSumData.Max[stIdx])
} else {
stationSumIdxMap[station] = stationIdx
stationSumData.TempSum[stationIdx] = stationData.TempSum[idx]
stationSumData.Count[stationIdx] = stationData.Count[idx]
stationSumData.Min[stationIdx] = stationData.Min[idx]
stationSumData.Max[stationIdx] = stationData.Max[idx]
stationIdx++
}
}
}
result <- resultType{
Temps: stationSumData,
IdxMap: stationSumIdxMap,
}
}
func generateChunkIndices(numCPUs int, size int64, chunkSize int64, err error, file *os.File, fileName string) []chunk {
chunkList := make([]chunk, 0, numCPUs)
chunkList = append(chunkList, chunk{
StartIdx: 0,
EndIdx: size - 1,
})
var readOff int64 = chunkSize
buffer := make([]byte, 150)
for cpuIdx := 1; cpuIdx < numCPUs; cpuIdx++ {
_, err = file.ReadAt(buffer, readOff)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading file '%s' for chunking:\n%s\n", fileName, err)
os.Exit(4)
}
newlineIdx := bytes.IndexByte(buffer, '\n')
if newlineIdx < 0 {
chunkList[cpuIdx-1].EndIdx = size - 1
break
}
chunkList = append(chunkList, chunk{
StartIdx: readOff + int64(newlineIdx) + 1,
EndIdx: size - 1,
})
chunkList[cpuIdx-1].EndIdx = readOff + int64(newlineIdx)
readOff += chunkSize
}
return chunkList
}
type resultType struct {
Temps stationTemperatures
IdxMap map[string]int
}
func processChunk(chunk chunk, file *os.File, channel chan resultType) {
content := make([]byte, chunk.EndIdx-chunk.StartIdx+1)
_, err := file.ReadAt(content, chunk.StartIdx)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading data file at offset %d, len %d:\n%s\n",
chunk.StartIdx, chunk.EndIdx-chunk.StartIdx+1, err)
os.Exit(2)
}
stationData := stationTemperatures{
TempSum: make([]int, 10_000),
Count: make([]uint, 10_000),
Min: make([]int, 10_000),
Max: make([]int, 10_000),
}
stationIdxMap := make(map[string]int, 10_000)
stationIdx := 0
// We suppose the file is valid, without a single error.
// Not a single error check is made.
for len(content) > 0 {
station := [100]byte{}
// Station name is not empty.
semiColonIdx := 1
station[0] = content[0]
currByte := content[1]
for currByte != ';' {
station[semiColonIdx] = currByte
semiColonIdx++
currByte = content[semiColonIdx]
}
var temperature int = 0
var negate = false
if content[semiColonIdx+1] == '-' {
negate = true
content = content[semiColonIdx+2:]
} else {
content = content[semiColonIdx+1:]
}
// Either `N.N\n` or `NN.N\n`
if content[1] == '.' {
temperature = int(content[0])*10 + int(content[2]) - '0'*11
content = content[4:]
} else {
temperature = int(content[0])*100 + int(content[1])*10 + int(content[3]) - '0'*111
content = content[5:]
}
if negate {
temperature *= -1
}
stIdx, ok := stationIdxMap[string(station[:semiColonIdx])]
if ok {
stationData.TempSum[stIdx] += temperature
stationData.Count[stIdx]++
stationData.Min[stIdx] = min(stationData.Min[stIdx], temperature)
stationData.Max[stIdx] = max(stationData.Max[stIdx], temperature)
} else {
stationIdxMap[string(station[:semiColonIdx])] = stationIdx
stationData.TempSum[stationIdx] = temperature
stationData.Count[stationIdx] = 1
stationData.Min[stationIdx] = temperature
stationData.Max[stationIdx] = temperature
stationIdx++
}
}
channel <- resultType{Temps: stationData, IdxMap: stationIdxMap}
}
func roundJava(x float64) float64 {
rounded := math.Trunc(x)
if x < 0.0 && rounded-x == 0.5 {
// return
} else if math.Abs(x-rounded) >= 0.5 {
rounded += math.Copysign(1, x)
}
// oh, another hardcoded `-0.0` to `0.0` conversion.
if rounded == 0 {
return 0.0
}
return rounded / 10.0
}