Skip to content

Instantly share code, notes, and snippets.

@felixge
Last active February 4, 2020 14:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felixge/aa70fc97e893a7eb0bd4c801f8f5b901 to your computer and use it in GitHub Desktop.
Save felixge/aa70fc97e893a7eb0bd4c801f8f5b901 to your computer and use it in GitHub Desktop.
$ time wc test.txt
16500000 49252094 2059004431 test.txt
real 0m5.930s
user 0m5.491s
sys 0m0.374s
$ go build wc.go && time ./wc test.txt
16500000 49252094 2059004431
real 0m2.947s
user 0m2.620s
sys 0m0.299s
package main
import (
"flag"
"fmt"
"io"
"os"
)
func main() {
if err := run(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func run() error {
flag.Parse()
f, err := os.Open(flag.Arg(0))
if err != nil {
return err
}
defer f.Close()
var (
ls int
ws int
bs int
wasSpace bool
)
buf := make([]byte, 16*4096)
for {
n, err := f.Read(buf)
if err == io.EOF {
break
} else if err != nil {
return err
}
bs += n
for i := 0; i < n; i++ {
switch buf[i] {
case '\n':
ls++
fallthrough
case ' ':
if !wasSpace {
ws++
wasSpace = true
}
default:
wasSpace = false
}
}
}
if !wasSpace {
ws++
}
fmt.Printf("%d %d %d\n", ls, ws, bs)
return nil
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment