Created
August 18, 2018 05:18
-
-
Save yoppi/dc12bec01e900ead6a1f2a6584bf6648 to your computer and use it in GitHub Desktop.
Fileを読み込むやつ
This file contains hidden or 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
$ ./file_read [~/d/src/go] | |
ReadFile:148545 elapsed:167.706µs | |
ReadLine:144946 elapsed:209.144µs | |
Scanner:144946 elapsed:553.246µs |
This file contains hidden or 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 ( | |
"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