Skip to content

Instantly share code, notes, and snippets.

@felixge

felixge/run-wc.txt

Last active Feb 4, 2020
Embed
What would you like to do?
$ 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