├── LICENSE ├── README.md ├── azure-pipelines.yml ├── build.sh ├── rev0 └── readfile0.go ├── rev1 └── readfile1.go ├── rev2 └── readfile2.go ├── rev3 └── readfile3.go ├── rev4 └── readfile4.go ├── rev5 └── readfile5.go ├── rev6 └── readfile6.go ├── rev7 └── readfile7.go ├── rev8 └── readfile8.go ├── rev9 └── readfile9.go ├── run.sh ├── run_all.sh └── utils └── install_fec_data.sh /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build Status](https://dev.azure.com/marcellanz/file-read-challenge-go/_apis/build/status/marcellanz.file-read-challenge-go?branchName=master)](https://dev.azure.com/marcellanz/file-read-challenge-go/_build/latest?definitionId=1&branchName=master) 2 | 3 | https://marcellanz.com/post/file-read-challenge/ 4 | 5 | >In January Stuart Marks published a blog post named ["Processing Large Files in Java"][marks_blog_post] as a response to a post by Paige Niedringhaus about ["Using Java to Read Really, Really Large Files"][niedringhaus_blog_post]. 6 | Niedringhaus there reports her experience with JavaScript to solve a "coding challenge" where a "very large file" has to be processed and four specific questions where asked about the processed file. After solving the challenge in JavaScript, Niedringhaus then moved forward and successfully implemented a solution to the challenge in Java as she was curious about Java and how to do it in that language. 7 | 8 | >This article starts where Marks left and tries to improve on the performance aspect of the code further; until we [_hit the wall_][hit_the_wall]. 9 | 10 | [hit_the_wall]:https://marcellanz.com/post/file-read-challenge/#conclusion-hitting-the-wall 11 | 12 | [marks_blog_post]: https://stuartmarks.wordpress.com/2019/01/11/processing-large-files-in-java/ 13 | [niedringhaus_blog_post]: https://itnext.io/using-java-to-read-really-really-large-files-a6f8a3f44649 -------------------------------------------------------------------------------- /azure-pipelines.yml: -------------------------------------------------------------------------------- 1 | # Starter pipeline 2 | # Start with a minimal pipeline that you can customize to build and deploy your code. 3 | # Add steps that build, run tests, deploy, and more: 4 | # https://aka.ms/yaml 5 | 6 | trigger: 7 | - master 8 | 9 | pool: 10 | vmImage: 'Ubuntu-16.04' 11 | 12 | variables: 13 | GOBIN: '$(GOPATH)/bin' # Go binaries path 14 | GOROOT: '/usr/local/go1.11' # Go installation path 15 | GOPATH: '$(system.defaultWorkingDirectory)/gopath' # Go workspace path 16 | modulePath: '$(GOPATH)/src/github.com/$(build.repository.name)' # Path to the module's code 17 | 18 | steps: 19 | - script: | 20 | mkdir -p '$(GOBIN)' 21 | mkdir -p '$(GOPATH)/pkg' 22 | mkdir -p '$(modulePath)' 23 | shopt -s extglob 24 | shopt -s dotglob 25 | mv !(gopath) '$(modulePath)' 26 | echo '##vso[task.prependpath]$(GOBIN)' 27 | echo '##vso[task.prependpath]$(GOROOT)/bin' 28 | displayName: 'Set up the Go workspace' 29 | 30 | - script: | 31 | go version 32 | go get -v -t -d ./... 33 | workingDirectory: '$(modulePath)' 34 | displayName: 'Get dependencies' 35 | 36 | - script: | 37 | bash build.sh 38 | workingDirectory: '$(modulePath)' 39 | continueOnError: 'false' 40 | displayName: 'Build app' 41 | 42 | - script: | 43 | wget -P data/indiv18/ $(benchmarkDataUrl)/itcont_1e6.txt.gz 44 | gunzip data/indiv18/itcont_1e6.txt.gz 45 | workingDirectory: '$(modulePath)' 46 | continueOnError: 'false' 47 | displayName: 'Prepare benchmarks' 48 | 49 | - script: | 50 | ./run_all.sh data/indiv18/itcont_1e6.txt 51 | workingDirectory: '$(modulePath)' 52 | continueOnError: 'false' 53 | displayName: 'Run benchmarks' -------------------------------------------------------------------------------- /build.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | mkdir -p bin 4 | GOBIN=`pwd`/bin go install ./... -------------------------------------------------------------------------------- /rev0/readfile0.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "regexp" 9 | "strings" 10 | "time" 11 | ) 12 | 13 | func main() { 14 | start := time.Now() 15 | file, err := os.Open(os.Args[1]) 16 | if err != nil { 17 | log.Fatal(err) 18 | } 19 | defer file.Close() 20 | 21 | firstNamePat := regexp.MustCompile(", \\s*([^, ]+)") 22 | names := make([]string, 0) 23 | firstNames := make([]string, 0) 24 | dates := make([]string, 0) 25 | commonName := "" 26 | commonCount := 0 27 | 28 | scanner := bufio.NewScanner(file) 29 | for scanner.Scan() { 30 | text := scanner.Text() 31 | 32 | // get all the names 33 | split := strings.SplitN(text, "|", 9) 34 | name := strings.TrimSpace(split[7]) 35 | names = append(names, name) 36 | 37 | // extract first names 38 | if matches := firstNamePat.FindAllStringSubmatch(name, 1); len(matches) > 0 { 39 | firstNames = append(firstNames, matches[0][1]) 40 | } 41 | 42 | // extract dates 43 | chars := strings.TrimSpace(split[4])[:6] 44 | date := chars[:4] + "-" + chars[4:6] 45 | dates = append(dates, date) 46 | } 47 | 48 | // report c2: names at index 49 | fmt.Printf("Name: %s at index: %v\n", names[0], 0) 50 | fmt.Printf("Name: %s at index: %v\n", names[432], 432) 51 | fmt.Printf("Name: %s at index: %v\n", names[43243], 43243) 52 | fmt.Printf("Name time: %v\n", time.Since(start)) 53 | 54 | // report c1: total number of lines 55 | fmt.Printf("Total file line count: %v\n", len(names)) 56 | fmt.Printf("Line count time: %v\n", time.Since(start)) 57 | 58 | // report c3: donation frequency 59 | dateMap := make(map[string]int) 60 | for _, date := range dates { 61 | dateMap[date] += 1 62 | } 63 | for k, v := range dateMap { 64 | fmt.Printf("Donations per month and year: %v and donation count: %v\n", k, v) 65 | } 66 | fmt.Printf("Donations time: %v\n", time.Since(start)) 67 | 68 | // report c4: most common firstName 69 | nameMap := make(map[string]int) 70 | nameCount := 0 // new count 71 | for _, name := range firstNames { 72 | nameCount = nameMap[name] + 1 73 | nameMap[name] = nameCount 74 | if nameCount > commonCount { 75 | commonName = name 76 | commonCount = nameCount 77 | } 78 | } 79 | fmt.Printf("The most common first name is: %s and it occurs: %v times.\n", commonName, commonCount) 80 | fmt.Printf("Most common name time: %v\n", time.Since(start)) 81 | } 82 | -------------------------------------------------------------------------------- /rev1/readfile1.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "regexp" 9 | "strings" 10 | "sync" 11 | "time" 12 | ) 13 | 14 | func main() { 15 | start := time.Now() 16 | file, err := os.Open(os.Args[1]) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer file.Close() 21 | 22 | firstNamePat := regexp.MustCompile(", \\s*([^, ]+)") 23 | names := make([]string, 0) 24 | firstNames := make([]string, 0) 25 | dates := make([]string, 0) 26 | commonName := "" 27 | commonCount := 0 28 | scanner := bufio.NewScanner(file) 29 | namesC := make(chan string) 30 | firstNamesC := make(chan string) 31 | datesC := make(chan string) 32 | wg := sync.WaitGroup{} 33 | 34 | go func() { 35 | for { 36 | select { 37 | case n, ok := <-namesC: 38 | if ok { 39 | names = append(names, n) 40 | wg.Done() 41 | } 42 | case fn, ok := <-firstNamesC: 43 | if ok { 44 | firstNames = append(firstNames, fn) 45 | wg.Done() 46 | } 47 | case d, ok := <-datesC: 48 | if ok { 49 | dates = append(dates, d) 50 | wg.Done() 51 | } 52 | } 53 | } 54 | }() 55 | 56 | for scanner.Scan() { 57 | text := scanner.Text() 58 | wg.Add(3) 59 | go func() { 60 | // get all the names 61 | split := strings.SplitN(text, "|", 9) 62 | name := strings.TrimSpace(split[7]) 63 | namesC <- name 64 | 65 | // extract first names 66 | if matches := firstNamePat.FindAllStringSubmatch(name, 1); len(matches) > 0 { 67 | firstNamesC <- matches[0][1] 68 | } else { 69 | wg.Add(-1) 70 | } 71 | 72 | // extract dates 73 | chars := strings.TrimSpace(split[4])[:6] 74 | date := chars[:4] + "-" + chars[4:6] 75 | datesC <- date 76 | }() 77 | } 78 | wg.Wait() 79 | close(namesC) 80 | close(firstNamesC) 81 | close(datesC) 82 | 83 | // report c2: names at index 84 | fmt.Printf("Name: %s at index: %v\n", names[0], 0) 85 | fmt.Printf("Name: %s at index: %v\n", names[432], 432) 86 | fmt.Printf("Name: %s at index: %v\n", names[43243], 43243) 87 | fmt.Printf("Name time: %v\n", time.Since(start)) 88 | 89 | // report c1: total number of lines 90 | fmt.Printf("Total file line count: %v\n", len(names)) 91 | fmt.Printf("Line count time: %v\n", time.Since(start)) 92 | 93 | // report c3: donation frequency 94 | dateMap := make(map[string]int) 95 | for _, date := range dates { 96 | dateMap[date] += 1 97 | } 98 | for k, v := range dateMap { 99 | fmt.Printf("Donations per month and year: %v and donation count: %v\n", k, v) 100 | } 101 | fmt.Printf("Donations time: %v\n", time.Since(start)) 102 | 103 | // report c4: most common firstName 104 | nameMap := make(map[string]int) 105 | nameCount := 0 // new count 106 | for _, name := range firstNames { 107 | nameCount = nameMap[name] + 1 108 | nameMap[name] = nameCount 109 | if nameCount > commonCount { 110 | commonName = name 111 | commonCount = nameCount 112 | } 113 | } 114 | fmt.Printf("The most common first name is: %s and it occurs: %v times.\n", commonName, commonCount) 115 | fmt.Printf("Most common name time: %v\n", time.Since(start)) 116 | } 117 | -------------------------------------------------------------------------------- /rev2/readfile2.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "regexp" 9 | "strings" 10 | "sync" 11 | "time" 12 | ) 13 | 14 | func main() { 15 | start := time.Now() 16 | file, err := os.Open(os.Args[1]) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer file.Close() 21 | 22 | firstNamePat := regexp.MustCompile(", \\s*([^, ]+)") 23 | names := make([]string, 0) 24 | firstNames := make([]string, 0) 25 | dates := make([]string, 0) 26 | commonName := "" 27 | commonCount := 0 28 | scanner := bufio.NewScanner(file) 29 | 30 | type entry struct { 31 | firstName string 32 | name string 33 | date string 34 | wg *sync.WaitGroup 35 | } 36 | entries := make(chan entry) 37 | wg := sync.WaitGroup{} 38 | 39 | go func() { 40 | for { 41 | select { 42 | case entry, ok := <-entries: 43 | if ok { 44 | if entry.firstName != "" { 45 | firstNames = append(firstNames, entry.firstName) 46 | } 47 | names = append(names, entry.name) 48 | dates = append(dates, entry.date) 49 | entry.wg.Done() 50 | } 51 | } 52 | } 53 | }() 54 | 55 | linesChunkLen := 64 * 1024 56 | lines := make([]string, 0, 0) 57 | for scanner.Scan() { 58 | line := scanner.Text() 59 | lines = append(lines, line) 60 | if len(lines) == linesChunkLen { 61 | wg.Add(len(lines)) 62 | process := lines 63 | go func() { 64 | for _, text := range process { 65 | // get all the names 66 | e := entry{wg: &wg} 67 | split := strings.SplitN(text, "|", 9) 68 | name := strings.TrimSpace(split[7]) 69 | e.name = name 70 | 71 | // extract first names 72 | if matches := firstNamePat.FindAllStringSubmatch(name, 1); len(matches) > 0 { 73 | e.firstName = matches[0][1] 74 | } 75 | // extract dates 76 | chars := strings.TrimSpace(split[4])[:6] 77 | e.date = chars[:4] + "-" + chars[4:6] 78 | entries <- e 79 | } 80 | }() 81 | lines = make([]string, 0, linesChunkLen) 82 | } 83 | } 84 | wg.Wait() 85 | close(entries) 86 | 87 | // report c2: names at index 88 | fmt.Printf("Name: %s at index: %v\n", names[0], 0) 89 | fmt.Printf("Name: %s at index: %v\n", names[432], 432) 90 | fmt.Printf("Name: %s at index: %v\n", names[43243], 43243) 91 | fmt.Printf("Name time: %v\n", time.Since(start)) 92 | 93 | // report c1: total number of lines 94 | fmt.Printf("Total file line count: %v\n", len(names)) 95 | fmt.Printf("Line count time: %v\n", time.Since(start)) 96 | 97 | // report c3: donation frequency 98 | dateMap := make(map[string]int) 99 | for _, date := range dates { 100 | dateMap[date] += 1 101 | } 102 | for k, v := range dateMap { 103 | fmt.Printf("Donations per month and year: %v and donation count: %v\n", k, v) 104 | } 105 | fmt.Printf("Donations time: %v\n", time.Since(start)) 106 | 107 | // report c4: most common firstName 108 | nameMap := make(map[string]int) 109 | nameCount := 0 // new count 110 | for _, name := range firstNames { 111 | nameCount = nameMap[name] + 1 112 | nameMap[name] = nameCount 113 | if nameCount > commonCount { 114 | commonName = name 115 | commonCount = nameCount 116 | } 117 | } 118 | fmt.Printf("The most common first name is: %s and it occurs: %v times.\n", commonName, commonCount) 119 | fmt.Printf("Most common name time: %v\n", time.Since(start)) 120 | } 121 | -------------------------------------------------------------------------------- /rev3/readfile3.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "regexp" 9 | "strings" 10 | "sync" 11 | "time" 12 | ) 13 | 14 | func main() { 15 | start := time.Now() 16 | file, err := os.Open(os.Args[1]) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer file.Close() 21 | 22 | firstNamePat := regexp.MustCompile(", \\s*([^, ]+)") 23 | names := make([]string, 0) 24 | firstNames := make([]string, 0) 25 | dates := make([]string, 0) 26 | commonName := "" 27 | commonCount := 0 28 | scanner := bufio.NewScanner(file) 29 | 30 | type entry struct { 31 | firstName string 32 | name string 33 | date string 34 | wg *sync.WaitGroup 35 | } 36 | entriesC := make(chan []entry) 37 | wg := sync.WaitGroup{} 38 | 39 | go func() { 40 | for { 41 | select { 42 | case entries, ok := <-entriesC: 43 | if ok { 44 | for _, entry := range entries { 45 | if entry.firstName != "" { 46 | firstNames = append(firstNames, entry.firstName) 47 | } 48 | names = append(names, entry.name) 49 | dates = append(dates, entry.date) 50 | entry.wg.Done() 51 | } 52 | } 53 | } 54 | } 55 | }() 56 | 57 | linesChunkLen := 64 * 1024 58 | lines := make([]string, 0, 0) 59 | scanner.Scan() 60 | for { 61 | lines = append(lines, scanner.Text()) 62 | willScan := scanner.Scan() 63 | if len(lines) == linesChunkLen || !willScan { 64 | toProcess := lines 65 | wg.Add(len(toProcess)) 66 | go func() { 67 | entries := make([]entry, 0, len(toProcess)) 68 | for _, text := range toProcess { 69 | // get all the names 70 | entry := entry{wg: &wg} 71 | split := strings.SplitN(text, "|", 9) 72 | name := strings.TrimSpace(split[7]) 73 | entry.name = name 74 | 75 | // extract first names 76 | if matches := firstNamePat.FindAllStringSubmatch(name, 1); len(matches) > 0 { 77 | entry.firstName = matches[0][1] 78 | } 79 | // extract dates 80 | chars := strings.TrimSpace(split[4])[:6] 81 | entry.date = chars[:4] + "-" + chars[4:6] 82 | entries = append(entries, entry) 83 | } 84 | entriesC <- entries 85 | }() 86 | lines = make([]string, 0, linesChunkLen) 87 | } 88 | if !willScan { 89 | break 90 | } 91 | } 92 | wg.Wait() 93 | close(entriesC) 94 | 95 | // report c2: names at index 96 | fmt.Printf("Name: %s at index: %v\n", names[0], 0) 97 | fmt.Printf("Name: %s at index: %v\n", names[432], 432) 98 | fmt.Printf("Name: %s at index: %v\n", names[43243], 43243) 99 | fmt.Printf("Name time: %v\n", time.Since(start)) 100 | 101 | // report c1: total number of lines 102 | fmt.Printf("Total file line count: %v\n", len(names)) 103 | fmt.Printf("Line count time: %v\n", time.Since(start)) 104 | 105 | // report c3: donation frequency 106 | dateMap := make(map[string]int) 107 | for _, date := range dates { 108 | dateMap[date] += 1 109 | } 110 | for k, v := range dateMap { 111 | fmt.Printf("Donations per month and year: %v and donation count: %v\n", k, v) 112 | } 113 | fmt.Printf("Donations time: %v\n", time.Since(start)) 114 | 115 | // report c4: most common firstName 116 | nameMap := make(map[string]int) 117 | nameCount := 0 118 | for _, name := range firstNames { 119 | nameCount = nameMap[name] + 1 120 | nameMap[name] = nameCount 121 | if nameCount > commonCount { 122 | commonName = name 123 | commonCount = nameCount 124 | } 125 | } 126 | fmt.Printf("The most common first name is: %s and it occurs: %v times.\n", commonName, commonCount) 127 | fmt.Printf("Most common name time: %v\n", time.Since(start)) 128 | } 129 | -------------------------------------------------------------------------------- /rev4/readfile4.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "regexp" 9 | "strings" 10 | "sync" 11 | "time" 12 | ) 13 | 14 | func main() { 15 | start := time.Now() 16 | file, err := os.Open(os.Args[1]) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer file.Close() 21 | 22 | firstNamePat := regexp.MustCompile(", \\s*([^, ]+)") 23 | names := make([]string, 0) 24 | firstNames := make([]string, 0) 25 | dates := make([]string, 0) 26 | commonName := "" 27 | commonCount := 0 28 | scanner := bufio.NewScanner(file) 29 | 30 | type entry struct { 31 | firstName string 32 | name string 33 | date string 34 | } 35 | mutex := sync.Mutex{} 36 | wg := sync.WaitGroup{} 37 | 38 | linesChunkLen := 64 * 1024 39 | lines := make([]string, 0, 0) 40 | scanner.Scan() 41 | for { 42 | lines = append(lines, scanner.Text()) 43 | willScan := scanner.Scan() 44 | if len(lines) == linesChunkLen || !willScan { 45 | toProcess := lines 46 | wg.Add(len(toProcess)) 47 | go func() { 48 | entries := make([]entry, 0, len(toProcess)) 49 | for _, text := range toProcess { 50 | // get all the names 51 | entry := entry{} 52 | split := strings.SplitN(text, "|", 9) 53 | name := strings.TrimSpace(split[7]) 54 | entry.name = name 55 | 56 | // extract first names 57 | if matches := firstNamePat.FindAllStringSubmatch(name, 1); len(matches) > 0 { 58 | entry.firstName = matches[0][1] 59 | } 60 | // extract dates 61 | chars := strings.TrimSpace(split[4])[:6] 62 | entry.date = chars[:4] + "-" + chars[4:6] 63 | entries = append(entries, entry) 64 | } 65 | mutex.Lock() 66 | for _, entry := range entries { 67 | if entry.firstName != "" { 68 | firstNames = append(firstNames, entry.firstName) 69 | } 70 | names = append(names, entry.name) 71 | dates = append(dates, entry.date) 72 | } 73 | wg.Add(-len(entries)) 74 | mutex.Unlock() 75 | }() 76 | lines = make([]string, 0, linesChunkLen) 77 | } 78 | if !willScan { 79 | break 80 | } 81 | } 82 | wg.Wait() 83 | 84 | // report c2: names at index 85 | fmt.Printf("Name: %s at index: %v\n", names[0], 0) 86 | fmt.Printf("Name: %s at index: %v\n", names[432], 432) 87 | fmt.Printf("Name: %s at index: %v\n", names[43243], 43243) 88 | fmt.Printf("Name time: %v\n", time.Since(start)) 89 | 90 | // report c1: total number of lines 91 | fmt.Printf("Total file line count: %v\n", len(names)) 92 | fmt.Printf("Line count time: %v\n", time.Since(start)) 93 | 94 | // report c3: donation frequency 95 | dateMap := make(map[string]int) 96 | for _, date := range dates { 97 | dateMap[date] += 1 98 | } 99 | for k, v := range dateMap { 100 | fmt.Printf("Donations per month and year: %v and donation count: %v\n", k, v) 101 | } 102 | fmt.Printf("Donations time: %v\n", time.Since(start)) 103 | 104 | // report c4: most common firstName 105 | nameMap := make(map[string]int) 106 | nameCount := 0 107 | for _, name := range firstNames { 108 | nameCount = nameMap[name] + 1 109 | nameMap[name] = nameCount 110 | if nameCount > commonCount { 111 | commonName = name 112 | commonCount = nameCount 113 | } 114 | } 115 | fmt.Printf("The most common first name is: %s and it occurs: %v times.\n", commonName, commonCount) 116 | fmt.Printf("Most common name time: %v\n", time.Since(start)) 117 | } 118 | -------------------------------------------------------------------------------- /rev5/readfile5.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "regexp" 9 | "strings" 10 | "sync" 11 | "time" 12 | ) 13 | 14 | func main() { 15 | start := time.Now() 16 | file, err := os.Open(os.Args[1]) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer file.Close() 21 | 22 | firstNamePat := regexp.MustCompile(", \\s*([^, ]+)") 23 | names := make([]string, 0) 24 | firstNames := make([]string, 0) 25 | dates := make([]string, 0) 26 | commonName := "" 27 | commonCount := 0 28 | scanner := bufio.NewScanner(file) 29 | nameMap := make(map[string]int) 30 | dateMap := make(map[string]int) 31 | 32 | type entry struct { 33 | firstName string 34 | name string 35 | date string 36 | } 37 | mutex := &sync.Mutex{} 38 | wg := sync.WaitGroup{} 39 | 40 | linesChunkLen := 64 * 1024 41 | lines := make([]string, 0, linesChunkLen) 42 | scanner.Scan() 43 | for { 44 | lines = append(lines, scanner.Text()) 45 | willScan := scanner.Scan() 46 | if len(lines) == linesChunkLen || !willScan { 47 | toProcess := lines 48 | wg.Add(len(toProcess)) 49 | go func() { 50 | entries := make([]entry, 0, len(toProcess)) 51 | for _, text := range toProcess { 52 | // get all the names 53 | entry := entry{} 54 | split := strings.SplitN(text, "|", 9) 55 | name := strings.TrimSpace(split[7]) 56 | entry.name = name 57 | 58 | // extract first names 59 | if matches := firstNamePat.FindAllStringSubmatch(name, 1); len(matches) > 0 { 60 | entry.firstName = matches[0][1] 61 | } 62 | // extract dates 63 | chars := strings.TrimSpace(split[4])[:6] 64 | entry.date = chars[:4] + "-" + chars[4:6] 65 | entries = append(entries, entry) 66 | } 67 | mutex.Lock() 68 | for _, entry := range entries { 69 | if entry.firstName != "" { 70 | firstNames = append(firstNames, entry.firstName) 71 | nameCount := nameMap[entry.firstName] 72 | nameMap[entry.firstName] = nameCount + 1 73 | if nameCount+1 > commonCount { 74 | commonName = entry.firstName 75 | commonCount = nameCount + 1 76 | } 77 | } 78 | names = append(names, entry.name) 79 | dates = append(dates, entry.date) 80 | dateMap[entry.date]++ 81 | } 82 | wg.Add(-len(entries)) 83 | mutex.Unlock() 84 | }() 85 | lines = make([]string, 0, linesChunkLen) 86 | } 87 | if !willScan { 88 | break 89 | } 90 | } 91 | wg.Wait() 92 | 93 | // report c2: names at index 94 | fmt.Printf("Name: %s at index: %v\n", names[0], 0) 95 | fmt.Printf("Name: %s at index: %v\n", names[432], 432) 96 | fmt.Printf("Name: %s at index: %v\n", names[43243], 43243) 97 | fmt.Printf("Name time: %v\n", time.Since(start)) 98 | 99 | // report c1: total number of lines 100 | fmt.Printf("Total file line count: %v\n", len(names)) 101 | fmt.Printf("Line count time: %v\n", time.Since(start)) 102 | 103 | // report c3: donation frequency 104 | for k, v := range dateMap { 105 | fmt.Printf("Donations per month and year: %v and donation count: %v\n", k, v) 106 | } 107 | fmt.Printf("Donations time: %v\n", time.Since(start)) 108 | 109 | // report c4: most common firstName 110 | fmt.Printf("The most common first name is: %s and it occurs: %v times.\n", commonName, commonCount) 111 | fmt.Printf("Most common name time: %v\n", time.Since(start)) 112 | } 113 | -------------------------------------------------------------------------------- /rev6/readfile6.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "regexp" 9 | "strings" 10 | "sync" 11 | "sync/atomic" 12 | "time" 13 | ) 14 | 15 | func main() { 16 | start := time.Now() 17 | file, err := os.Open(os.Args[1]) 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | defer file.Close() 22 | 23 | firstNamePat := regexp.MustCompile(", \\s*([^, ]+)") 24 | names := make([]string, 0) 25 | firstNames := make([]string, 0) 26 | dates := make([]string, 0) 27 | commonName := "" 28 | commonCount := 0 29 | scanner := bufio.NewScanner(file) 30 | nameMap := make(map[string]int) 31 | dateMap := make(map[string]int) 32 | 33 | type entry struct { 34 | firstName string 35 | name string 36 | date string 37 | } 38 | 39 | linesChunkLen := 64 * 1024 40 | linesChunkPoolAllocated := int64(0) 41 | linesPool := sync.Pool{New: func() interface{} { 42 | lines := make([]string, 0, linesChunkLen) 43 | atomic.AddInt64(&linesChunkPoolAllocated, 1) 44 | return lines 45 | }} 46 | lines := linesPool.Get().([]string)[:0] 47 | 48 | entriesPoolAllocated := int64(0) 49 | entriesPool := sync.Pool{New: func() interface{} { 50 | entries := make([]entry, 0, linesChunkLen) 51 | atomic.AddInt64(&entriesPoolAllocated, 1) 52 | return entries 53 | }} 54 | mutex := &sync.Mutex{} 55 | wg := sync.WaitGroup{} 56 | 57 | scanner.Scan() 58 | for { 59 | lines = append(lines, scanner.Text()) 60 | willScan := scanner.Scan() 61 | if len(lines) == linesChunkLen || !willScan { 62 | linesToProcess := lines 63 | wg.Add(len(linesToProcess)) 64 | go func() { 65 | entries := entriesPool.Get().([]entry)[:0] 66 | for _, text := range linesToProcess { 67 | // get all the names 68 | entry := entry{} 69 | split := strings.SplitN(text, "|", 9) 70 | name := strings.TrimSpace(split[7]) 71 | entry.name = name 72 | 73 | // extract first names 74 | if matches := firstNamePat.FindAllStringSubmatch(name, 1); len(matches) > 0 { 75 | entry.firstName = matches[0][1] 76 | } 77 | // extract dates 78 | chars := strings.TrimSpace(split[4])[:6] 79 | entry.date = chars[:4] + "-" + chars[4:6] 80 | entries = append(entries, entry) 81 | } 82 | mutex.Lock() 83 | for _, entry := range entries { 84 | if entry.firstName != "" { 85 | firstNames = append(firstNames, entry.firstName) 86 | nameCount := nameMap[entry.firstName] 87 | nameMap[entry.firstName] = nameCount + 1 88 | if nameCount+1 > commonCount { 89 | commonName = entry.firstName 90 | commonCount = nameCount + 1 91 | } 92 | } 93 | names = append(names, entry.name) 94 | dates = append(dates, entry.date) 95 | dateMap[entry.date]++ 96 | } 97 | entriesPool.Put(entries) 98 | linesPool.Put(linesToProcess) 99 | wg.Add(-len(entries)) 100 | mutex.Unlock() 101 | }() 102 | lines = linesPool.Get().([]string)[:0] 103 | } 104 | if !willScan { 105 | break 106 | } 107 | } 108 | wg.Wait() 109 | 110 | // report c2: names at index 111 | fmt.Printf("Name: %s at index: %v\n", names[0], 0) 112 | fmt.Printf("Name: %s at index: %v\n", names[432], 432) 113 | fmt.Printf("Name: %s at index: %v\n", names[43243], 43243) 114 | fmt.Printf("Name time: %v\n", time.Since(start)) 115 | 116 | // report c1: total number of lines 117 | fmt.Printf("Total file line count: %v\n", len(names)) 118 | fmt.Printf("Line count time: %v\n", time.Since(start)) 119 | 120 | // report c3: donation frequency 121 | for k, v := range dateMap { 122 | fmt.Printf("Donations per month and year: %v and donation count: %v\n", k, v) 123 | } 124 | fmt.Printf("Donations time: %v\n", time.Since(start)) 125 | 126 | // report c4: most common firstName 127 | fmt.Printf("The most common first name is: %s and it occurs: %v times.\n", commonName, commonCount) 128 | fmt.Printf("Most common name time: %v\n", time.Since(start)) 129 | } 130 | -------------------------------------------------------------------------------- /rev7/readfile7.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "regexp" 9 | "strings" 10 | "sync" 11 | "sync/atomic" 12 | "time" 13 | ) 14 | 15 | func main() { 16 | start := time.Now() 17 | file, err := os.Open(os.Args[1]) 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | defer file.Close() 22 | 23 | firstNamePat := regexp.MustCompile(", \\s*[^, ]+") 24 | names := make([]string, 0) 25 | firstNames := make([]string, 0) 26 | dates := make([]string, 0) 27 | commonName := "" 28 | commonCount := 0 29 | scanner := bufio.NewScanner(file) 30 | nameMap := make(map[string]int) 31 | dateMap := make(map[string]int) 32 | 33 | type entry struct { 34 | firstName string 35 | name string 36 | date string 37 | } 38 | 39 | linesChunkLen := 64 * 1024 40 | linesChunkPoolAllocated := int64(0) 41 | linesPool := sync.Pool{New: func() interface{} { 42 | lines := make([]string, 0, linesChunkLen) 43 | atomic.AddInt64(&linesChunkPoolAllocated, 1) 44 | return lines 45 | }} 46 | lines := linesPool.Get().([]string)[:0] 47 | 48 | entriesPoolAllocated := int64(0) 49 | entriesPool := sync.Pool{New: func() interface{} { 50 | entries := make([]entry, 0, linesChunkLen) 51 | atomic.AddInt64(&entriesPoolAllocated, 1) 52 | return entries 53 | }} 54 | mutex := &sync.Mutex{} 55 | wg := sync.WaitGroup{} 56 | 57 | scanner.Scan() 58 | for { 59 | lines = append(lines, scanner.Text()) 60 | willScan := scanner.Scan() 61 | if len(lines) == linesChunkLen || !willScan { 62 | linesToProcess := lines 63 | wg.Add(len(linesToProcess)) 64 | go func() { 65 | entries := entriesPool.Get().([]entry)[:0] 66 | for _, text := range linesToProcess { 67 | // get all the names 68 | entry := entry{} 69 | split := strings.SplitN(text, "|", 9) 70 | name := strings.TrimSpace(split[7]) 71 | entry.name = name 72 | 73 | // extract first names 74 | if matched := firstNamePat.FindString(name); matched != "" { 75 | entry.firstName = matched[2:] 76 | } 77 | // extract dates 78 | chars := strings.TrimSpace(split[4])[:6] 79 | entry.date = chars[:4] + "-" + chars[4:6] 80 | entries = append(entries, entry) 81 | } 82 | mutex.Lock() 83 | for _, entry := range entries { 84 | if entry.firstName != "" { 85 | firstNames = append(firstNames, entry.firstName) 86 | nameCount := nameMap[entry.firstName] 87 | nameMap[entry.firstName] = nameCount + 1 88 | if nameCount+1 > commonCount { 89 | commonName = entry.firstName 90 | commonCount = nameCount + 1 91 | } 92 | } 93 | names = append(names, entry.name) 94 | dates = append(dates, entry.date) 95 | dateMap[entry.date]++ 96 | } 97 | entriesPool.Put(entries) 98 | linesPool.Put(linesToProcess) 99 | wg.Add(-len(entries)) 100 | mutex.Unlock() 101 | }() 102 | lines = linesPool.Get().([]string)[:0] 103 | } 104 | if !willScan { 105 | break 106 | } 107 | } 108 | wg.Wait() 109 | 110 | // report c2: names at index 111 | fmt.Printf("Name: %s at index: %v\n", names[0], 0) 112 | fmt.Printf("Name: %s at index: %v\n", names[432], 432) 113 | fmt.Printf("Name: %s at index: %v\n", names[43243], 43243) 114 | fmt.Printf("Name time: %v\n", time.Since(start)) 115 | 116 | // report c1: total number of lines 117 | fmt.Printf("Total file line count: %v\n", len(names)) 118 | fmt.Printf("Line count time: %v\n", time.Since(start)) 119 | 120 | // report c3: donation frequency 121 | for k, v := range dateMap { 122 | fmt.Printf("Donations per month and year: %v and donation count: %v\n", k, v) 123 | } 124 | fmt.Printf("Donations time: %v\n", time.Since(start)) 125 | 126 | // report c4: most common firstName 127 | fmt.Printf("The most common first name is: %s and it occurs: %v times.\n", commonName, commonCount) 128 | fmt.Printf("Most common name time: %v\n", time.Since(start)) 129 | } 130 | -------------------------------------------------------------------------------- /rev8/readfile8.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strings" 9 | "sync" 10 | "sync/atomic" 11 | "time" 12 | ) 13 | 14 | func main() { 15 | start := time.Now() 16 | file, err := os.Open(os.Args[1]) 17 | if err != nil { 18 | log.Fatal(err) 19 | } 20 | defer file.Close() 21 | 22 | names := make([]string, 0) 23 | firstNames := make([]string, 0) 24 | dates := make([]string, 0) 25 | commonName := "" 26 | commonCount := 0 27 | scanner := bufio.NewScanner(file) 28 | nameMap := make(map[string]int) 29 | dateMap := make(map[string]int) 30 | 31 | type entry struct { 32 | firstName string 33 | name string 34 | date string 35 | } 36 | 37 | linesChunkLen := 64 * 1024 38 | linesChunkPoolAllocated := int64(0) 39 | linesPool := sync.Pool{New: func() interface{} { 40 | lines := make([]string, 0, linesChunkLen) 41 | atomic.AddInt64(&linesChunkPoolAllocated, 1) 42 | return lines 43 | }} 44 | lines := linesPool.Get().([]string)[:0] 45 | 46 | entriesPoolAllocated := int64(0) 47 | entriesPool := sync.Pool{New: func() interface{} { 48 | entries := make([]entry, 0, linesChunkLen) 49 | atomic.AddInt64(&entriesPoolAllocated, 1) 50 | return entries 51 | }} 52 | mutex := &sync.Mutex{} 53 | wg := sync.WaitGroup{} 54 | 55 | scanner.Scan() 56 | for { 57 | lines = append(lines, scanner.Text()) 58 | willScan := scanner.Scan() 59 | if len(lines) == linesChunkLen || !willScan { 60 | linesToProcess := lines 61 | wg.Add(len(linesToProcess)) 62 | go func() { 63 | entries := entriesPool.Get().([]entry)[:0] 64 | for _, text := range linesToProcess { 65 | // get all the names 66 | entry := entry{} 67 | split := strings.SplitN(text, "|", 9) 68 | name := strings.TrimSpace(split[7]) 69 | entry.name = name 70 | 71 | // extract first names 72 | if name != "" { 73 | startOfName := strings.Index(name, ", ") + 2 74 | if endOfName := strings.Index(name[startOfName:], " "); endOfName < 0 { 75 | entry.firstName = name[startOfName:] 76 | } else { 77 | entry.firstName = name[startOfName : startOfName+endOfName] 78 | } 79 | if strings.HasSuffix(entry.firstName, ",") { 80 | entry.firstName = strings.Replace(entry.firstName, ",", "", -1) 81 | } 82 | } 83 | // extract dates 84 | chars := strings.TrimSpace(split[4])[:6] 85 | entry.date = chars[:4] + "-" + chars[4:6] 86 | entries = append(entries, entry) 87 | } 88 | mutex.Lock() 89 | for _, entry := range entries { 90 | if entry.firstName != "" { 91 | firstNames = append(firstNames, entry.firstName) 92 | nameCount := nameMap[entry.firstName] 93 | nameMap[entry.firstName] = nameCount + 1 94 | if nameCount+1 > commonCount { 95 | commonName = entry.firstName 96 | commonCount = nameCount + 1 97 | } 98 | } 99 | names = append(names, entry.name) 100 | dates = append(dates, entry.date) 101 | dateMap[entry.date]++ 102 | } 103 | entriesPool.Put(entries) 104 | linesPool.Put(linesToProcess) 105 | wg.Add(-len(entries)) 106 | mutex.Unlock() 107 | }() 108 | lines = linesPool.Get().([]string)[:0] 109 | } 110 | if !willScan { 111 | break 112 | } 113 | } 114 | wg.Wait() 115 | 116 | // report c2: names at index 117 | fmt.Printf("Name: %s at index: %v\n", names[0], 0) 118 | fmt.Printf("Name: %s at index: %v\n", names[432], 432) 119 | fmt.Printf("Name: %s at index: %v\n", names[43243], 43243) 120 | fmt.Printf("Name time: %v\n", time.Since(start)) 121 | 122 | // report c1: total number of lines 123 | fmt.Printf("Total file line count: %v\n", len(names)) 124 | fmt.Printf("Line count time: %v\n", time.Since(start)) 125 | 126 | // report c3: donation frequency 127 | for k, v := range dateMap { 128 | fmt.Printf("Donations per month and year: %v and donation count: %v\n", k, v) 129 | } 130 | fmt.Printf("Donations time: %v\n", time.Since(start)) 131 | 132 | // report c4: most common firstName 133 | fmt.Printf("The most common first name is: %s and it occurs: %v times.\n", commonName, commonCount) 134 | fmt.Printf("Most common name time: %v\n", time.Since(start)) 135 | } 136 | -------------------------------------------------------------------------------- /rev9/readfile9.go: -------------------------------------------------------------------------------- 1 | package main 2 | 3 | import ( 4 | "bufio" 5 | "fmt" 6 | "log" 7 | "os" 8 | "strconv" 9 | "strings" 10 | "sync" 11 | "sync/atomic" 12 | "time" 13 | ) 14 | 15 | func main() { 16 | start := time.Now() 17 | file, err := os.Open(os.Args[1]) 18 | if err != nil { 19 | log.Fatal(err) 20 | } 21 | defer file.Close() 22 | 23 | commonName := "" 24 | commonCount := 0 25 | scanner := bufio.NewScanner(file) 26 | nameMap := make(map[string]int) 27 | dateMap := make(map[int]int) 28 | 29 | namesCounted := false 30 | namesCount := 0 31 | fileLineCount := int64(0) 32 | 33 | type entry struct { 34 | firstName string 35 | name string 36 | date int 37 | } 38 | 39 | linesChunkLen := 64 * 1024 40 | linesChunkPoolAllocated := int64(0) 41 | linesPool := sync.Pool{New: func() interface{} { 42 | lines := make([]string, 0, linesChunkLen) 43 | atomic.AddInt64(&linesChunkPoolAllocated, 1) 44 | return lines 45 | }} 46 | lines := linesPool.Get().([]string)[:0] 47 | 48 | entriesPoolAllocated := int64(0) 49 | entriesPool := sync.Pool{New: func() interface{} { 50 | entries := make([]entry, 0, linesChunkLen) 51 | atomic.AddInt64(&entriesPoolAllocated, 1) 52 | return entries 53 | }} 54 | mutex := &sync.Mutex{} 55 | wg := sync.WaitGroup{} 56 | 57 | scanner.Scan() 58 | for { 59 | lines = append(lines, scanner.Text()) 60 | willScan := scanner.Scan() 61 | if len(lines) == linesChunkLen || !willScan { 62 | linesToProcess := lines 63 | wg.Add(len(linesToProcess)) 64 | go func() { 65 | atomic.AddInt64(&fileLineCount, int64(len(linesToProcess))) 66 | entries := entriesPool.Get().([]entry)[:0] 67 | for _, text := range linesToProcess { 68 | // get all the names 69 | entry := entry{} 70 | split := strings.SplitN(text, "|", 9) 71 | entry.name = strings.TrimSpace(split[7]) 72 | 73 | // extract first names 74 | if entry.name != "" { 75 | startOfName := strings.Index(entry.name, ", ") + 2 76 | if endOfName := strings.Index(entry.name[startOfName:], " "); endOfName < 0 { 77 | entry.firstName = entry.name[startOfName:] 78 | } else { 79 | entry.firstName = entry.name[startOfName : startOfName+endOfName] 80 | } 81 | if cs := strings.Index(entry.firstName, ","); cs > 0 { 82 | entry.firstName = entry.firstName[:cs] 83 | } 84 | } 85 | // extract dates 86 | entry.date, _ = strconv.Atoi(split[4][:6]) 87 | entries = append(entries, entry) 88 | } 89 | linesPool.Put(linesToProcess) 90 | mutex.Lock() 91 | for _, entry := range entries { 92 | if len(entry.firstName) != 0 { 93 | nameCount := nameMap[entry.firstName] + 1 94 | nameMap[entry.firstName] = nameCount 95 | if nameCount > commonCount { 96 | commonCount = nameCount 97 | commonName = entry.firstName 98 | } 99 | } 100 | if namesCounted == false { 101 | if namesCount == 0 { 102 | fmt.Printf("Name: %s at index: %v\n", entry.name, 0) 103 | } else if namesCount == 432 { 104 | fmt.Printf("Name: %s at index: %v\n", entry.name, 432) 105 | } else if namesCount == 43243 { 106 | fmt.Printf("Name: %s at index: %v\n", entry.name, 43243) 107 | namesCounted = true 108 | } 109 | namesCount++ 110 | } 111 | dateMap[entry.date]++ 112 | } 113 | mutex.Unlock() 114 | entriesPool.Put(entries) 115 | wg.Add(-len(entries)) 116 | }() 117 | lines = linesPool.Get().([]string)[:0] 118 | } 119 | if !willScan { 120 | break 121 | } 122 | } 123 | wg.Wait() 124 | 125 | // report c2: names at index 126 | fmt.Printf("Name time: %v\n", time.Since(start)) 127 | 128 | // report c1: total number of lines 129 | fmt.Printf("Total file line count: %v\n", fileLineCount) 130 | fmt.Printf("Line count time: %v\n", time.Since(start)) 131 | 132 | // report c3: donation frequency 133 | for k, v := range dateMap { 134 | fmt.Printf("Donations per month and year: %v and donation count: %v\n", k, v) 135 | } 136 | fmt.Printf("Donations time: %v\n", time.Since(start)) 137 | 138 | // report c4: most common firstName 139 | fmt.Printf("The most common first name is: %s and it occurs: %v times.\n", commonName, commonCount) 140 | fmt.Printf("Most common name time: %v\n", time.Since(start)) 141 | } 142 | -------------------------------------------------------------------------------- /run.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | go run rev${1}/readfile${1}.go ./data/indiv18/itcont.txt 4 | -------------------------------------------------------------------------------- /run_all.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | start=0 4 | end=9 5 | for ((i=start; i<=end; i++)) 6 | do 7 | ./bin/rev${i} ${1} 8 | ./bin/rev${i} ${1} 9 | ./bin/rev${i} ${1} 10 | done -------------------------------------------------------------------------------- /utils/install_fec_data.sh: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | curl -L -O https://www.fec.gov/files/bulk-downloads/2018/indiv18.zip && 4 | unzip -p indiv18 itcont.txt | head -n 18245416 > itcont.txt && 5 | rm indiv18.zip && 6 | mkdir -p ./data/indiv18 && 7 | mv itcont.txt ./data/indiv18/ 8 | --------------------------------------------------------------------------------