/
go_parallel_eq.go
376 lines (331 loc) · 9.57 KB
/
go_parallel_eq.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
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
// SPDX-FileCopyrightText: Copyright 2024 Roland Csaszar
// SPDX-License-Identifier: MIT
//
// Project: 1-billion-row-challenge
// File: go_parallel_eq.go
// Date: 23.Mar.2024
//
// =============================================================================
// Uses FNV hash algorithm: http://www.isthe.com/chongo/tech/comp/fnv/index.html
package main
import (
"bytes"
"fmt"
"math"
"os"
"runtime"
"sort"
"syscall"
)
type stationTemperatures struct {
TempSum []int
Count []uint
Min []int
Max []int
}
type chunk struct {
StartIdx int64
EndIdx int64
}
type mapStruct struct {
Station string
idx int
}
const (
numBits = 16
mask = (1 << numBits) - 1
fnvPrime = 16777619
fnvOffsetBasis = 2166136261
)
func fnvHash(s string) uint32 {
var hash uint32 = fnvOffsetBasis
for _, ch := range s {
hash ^= uint32(ch)
hash *= fnvPrime
}
return hash & mask
}
func main() {
if len(os.Args) < 2 {
fmt.Fprintln(os.Stderr, "Error: no data file to process given! Exiting.")
os.Exit(1)
}
numCPUs := 10 * runtime.NumCPU()
fileName := os.Args[1]
// f, err := os.Create("cpu.prof")
// if err != nil {
// log.Fatal(err)
// }
// pprof.StartCPUProfile(f)
// defer pprof.StopCPUProfile()
// f1, err := os.Create("trace.prof")
// if err != nil {
// log.Fatal(err)
// }
// trace.Start(f1)
// defer trace.Stop()
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()
stat, 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 := int64(stat.Size())
chunkSize := size / int64(numCPUs)
content, err := syscall.Mmap(int(file.Fd()), 0, int(size), syscall.PROT_READ, syscall.MAP_SHARED)
if err != nil {
fmt.Fprintf(os.Stderr, "Error mapping file '%s':\n%s\n", fileName, err)
os.Exit(4)
}
defer func() {
err := syscall.Munmap(content)
if err != nil {
fmt.Fprintf(os.Stderr, "Error unmapping file '%s':\n%s\n", fileName, err)
os.Exit(5)
}
}()
chunkList := generateChunkIndices(numCPUs, size, chunkSize, err, file, fileName)
channels := make([]chan resultType, numCPUs)
for idx, chunk := range chunkList {
// non-blocking channels
channels[idx] = make(chan resultType, 1)
go processChunk(content[chunk.StartIdx:chunk.EndIdx+1], channels[idx])
}
numSumChans := 2
numToSum := numCPUs / numSumChans
sumChannels := make([]chan resultType, numSumChans)
for i := 0; i < numSumChans; i++ {
sumChannels[i] = make(chan resultType, 1)
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([]mapStruct, mask+1)
stationIdx := 0
for _, channel := range sumChannels {
result := <-channel
stationData := result.Temps
stationIdxMap := result.IdxMap
for _, station := range stationIdxMap {
if station.Station == "" {
continue
}
idx := station.idx
nameHash := fnvHash(station.Station)
for i := nameHash; i < mask+1; i++ {
if bytes.Equal([]byte(stationSumIdxMap[i].Station), []byte(station.Station)) {
stIdx := stationSumIdxMap[i].idx
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])
break
} else if stationSumIdxMap[i].Station == "" {
stationSumIdxMap[i].idx = stationIdx
stationSumIdxMap[i].Station = station.Station
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++
break
}
}
}
}
keys := make([]string, 0, mask+1)
for _, key := range stationSumIdxMap {
if key.Station != "" {
keys = append(keys, key.Station)
}
}
sort.Strings(keys)
fmt.Printf("{")
for i, station := range keys {
if i > 0 {
fmt.Printf(", ")
}
idx := 0
nameHash := fnvHash(station)
for i := nameHash; i < mask+1; i++ {
if stationSumIdxMap[i].Station == station {
idx = stationSumIdxMap[i].idx
break
}
}
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([]mapStruct, mask+1)
stationIdx := 0
for _, channel := range channels {
result := <-channel
stationData := result.Temps
stationIdxMap := result.IdxMap
for _, station := range stationIdxMap {
if station.Station == "" {
continue
}
nameHash := fnvHash(station.Station)
idx := station.idx
for i := nameHash; i < mask+1; i++ {
if bytes.Equal([]byte(stationSumIdxMap[i].Station), []byte(station.Station)) {
stIdx := stationSumIdxMap[i].idx
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])
break
} else if stationSumIdxMap[i].Station == "" {
stationSumIdxMap[i].idx = stationIdx
stationSumIdxMap[i].Station = station.Station
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++
break
}
}
}
}
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 []mapStruct
}
func processChunk(content []byte, channel chan resultType) {
stationData := stationTemperatures{
TempSum: make([]int, 10_000),
Count: make([]uint, 10_000),
Min: make([]int, 10_000),
Max: make([]int, 10_000),
}
//colls := 0
stationIdxMap := make([]mapStruct, mask+1)
stationIdx := 0
station := [100]byte{}
// We suppose the file is valid, without a single error.
// Not a single error check is made.
for len(content) > 0 {
// Station name is not empty.
semiColonIdx := 1
station[0] = content[0]
currByte := content[1]
var nameHash uint32 = fnvOffsetBasis
for currByte != ';' {
station[semiColonIdx] = currByte
nameHash ^= uint32(currByte)
nameHash *= fnvPrime
semiColonIdx++
currByte = content[semiColonIdx]
}
nameHash &= mask
var temperature int = 0
negate := 1
if content[semiColonIdx+1] == '-' {
negate = -1
content = content[semiColonIdx+2:]
} else {
content = content[semiColonIdx+1:]
}
// Either `N.N\n` or `NN.N\n`
if content[1] == '.' {
temperature = negate * (int(content[0])*10 + int(content[2]) - 528)
content = content[4:]
} else {
temperature = negate * (int(content[0])*100 + int(content[1])*10 + int(content[3]) - 5328)
content = content[5:]
}
for i := nameHash; i < mask+1; i++ {
if bytes.Equal(station[:semiColonIdx], []byte(stationIdxMap[i].Station)) {
stIdx := stationIdxMap[i].idx
stationData.TempSum[stIdx] += temperature
stationData.Count[stIdx]++
stationData.Min[stIdx] = min(stationData.Min[stIdx], temperature)
stationData.Max[stIdx] = max(stationData.Max[stIdx], temperature)
break
} else if stationIdxMap[i].Station == "" {
stationIdxMap[i].Station = string(station[:semiColonIdx])
stationIdxMap[i].idx = stationIdx
stationData.TempSum[stationIdx] = temperature
stationData.Count[stationIdx] = 1
stationData.Min[stationIdx] = temperature
stationData.Max[stationIdx] = temperature
stationIdx++
break
}
// else {
// colls++
// }
}
}
//fmt.Fprintf(os.Stderr, "Station name collisions: %d\n", colls)
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
}