Skip to content

Instantly share code, notes, and snippets.

@yoppi
Created August 18, 2018 05:18
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 yoppi/dc12bec01e900ead6a1f2a6584bf6648 to your computer and use it in GitHub Desktop.
Save yoppi/dc12bec01e900ead6a1f2a6584bf6648 to your computer and use it in GitHub Desktop.
Fileを読み込むやつ
$ ./file_read [~/d/src/go]
ReadFile:148545 elapsed:167.706µs
ReadLine:144946 elapsed:209.144µs
Scanner:144946 elapsed:553.246µs
package main
import (
"bufio"
"fmt"
"io"
"io/ioutil"
"os"
"time"
)
func Scanner(filepath string) {
startAt := time.Now()
fd, err := os.Open(filepath)
if err != nil {
panic(err)
}
defer fd.Close()
scanner := bufio.NewScanner(fd)
var txtLen int
for scanner.Scan() {
line := scanner.Text()
txtLen += len(line)
}
fmt.Printf("Scanner:%d elapsed:%v\n", txtLen, time.Now().Sub(startAt))
}
func ReadEachLine(filepath string) {
startAt := time.Now()
fd, err := os.Open(filepath)
if err != nil {
panic(err)
}
defer fd.Close()
r := bufio.NewReader(fd)
var txtLen int
for {
line, _, err := r.ReadLine()
txtLen += len(line)
if err != nil {
if err == io.EOF {
break
}
panic(err)
}
}
fmt.Printf("ReadLine:%d elapsed:%v\n", txtLen, time.Now().Sub(startAt))
}
func ReadFile(filepath string) {
startAt := time.Now()
txt, err := ioutil.ReadFile(filepath)
if err != nil {
panic(err)
}
fmt.Printf("ReadFile:%d elapsed:%v\n", len(txt), time.Now().Sub(startAt))
}
func main() {
ReadFile("./alice30.txt")
ReadEachLine("./alice30.txt")
Scanner("./alice30.txt")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment