Created
February 17, 2017 14:36
-
-
Save Hubro/76e6b7c906c308b84b23188578b74483 to your computer and use it in GitHub Desktop.
Line counter written in Go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"bytes" | |
"fmt" | |
"io" | |
"os" | |
) | |
func main() { | |
args := os.Args[1:] | |
if len(args) != 1 { | |
fmt.Fprintln(os.Stderr, "Expected 1 argument: File path") | |
os.Exit(1) | |
} | |
path := args[0] | |
file, err := os.Open(path) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Failed to open file: %v", err) | |
os.Exit(1) | |
} | |
count, err := lineCounter(file) | |
if err != nil { | |
fmt.Fprintf(os.Stderr, "Encountered error while counting: %v", err) | |
os.Exit(1) | |
} | |
fmt.Println(count) | |
} | |
func lineCounter(r io.Reader) (int, error) { | |
buf := make([]byte, 32*1024) | |
count := 0 | |
lineSep := []byte{'\n'} | |
for { | |
c, err := r.Read(buf) | |
count += bytes.Count(buf[:c], lineSep) | |
switch { | |
case err == io.EOF: | |
return count, nil | |
case err != nil: | |
return count, err | |
} | |
} | |
} |
@Hubro Could I enter in this comparison the function I did to count lines?
In my comparison my function is at least four times faster than the one you are testing.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
func lineCounter
taken from this stackoverflow.com answer: http://stackoverflow.com/a/24563853/388916