Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions wordcount/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,23 @@ A simple timer has been used to track execution time.

Provide the name of the text file as a command line argument.

`go run main.go moby.txt`
`go run main.go shakespeare.txt`

Example file to use:
https://www.gutenberg.org/cache/epub/2701/pg2701.txt
https://www.gutenberg.org/ebooks/100


# Execution time

For base branch:
`"shakespeare.txt": 741200 words, duration: 3422897ms`

For this branch:
`"shakespeare.txt": 378586 words, duration: 30136ms`

Compare to word count:

`time wc -w shakespeare.txt `

`378588 shakespeare.txt`
`wc -w shakespeare.txt 0.01s user 0.00s system 76% cpu 0.016 total`
Binary file added wordcount/cpuprofile.pprof
Binary file not shown.
59 changes: 32 additions & 27 deletions wordcount/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,46 @@ package main

import (
"fmt"
"io"
"log"
"os"
"runtime/pprof"
"strings"
"time"
"unicode"
)

func readbyte(r io.Reader) (rune, error) {
var buf [1]byte
_, err := r.Read(buf[:])
return rune(buf[0]), err
}

func main() {
f, err := os.Open(os.Args[1])
// This version was implemented by Copilot

// Read the file
filePath := os.Args[1]
content, err := os.ReadFile(filePath)
if err != nil {
log.Fatalf("could not open file %q: %v", os.Args[1], err)
fmt.Println("Error reading file:", err)
return
}

start := time.Now()
words := 0
inword := false
for {
r, err := readbyte(f)
if err == io.EOF {
break
}
if err != nil {
log.Fatalf("could not read file %q: %v", os.Args[1], err)
}
if unicode.IsSpace(r) && inword {
words++
inword = false
}
inword = unicode.IsLetter(r)
fc, err := os.Create("cpuprofile.pprof")
if err != nil {
log.Fatal(err)
}
fmt.Printf("%q: %d words, duration: %dms\n", os.Args[1], words, time.Since(start)/1000)
pprof.StartCPUProfile(fc)
defer pprof.StopCPUProfile()

start := time.Now()

// Convert the content to string
text := string(content)

// Count the words
wordCount := countWords(text)

fmt.Printf("%q: %d words, duration: %dms\n", os.Args[1], wordCount, time.Since(start)/1000)
}

func countWords(text string) int {
// Split the text into words
words := strings.Fields(text)

// Return the count of words
return len(words)
}
Loading