2 回答
TA贡献1851条经验 获得超5个赞
package main
import (
"bufio"
"bytes"
"fmt"
"os"
)
func main() {
file, _ := os.Open("dic.dat")
scanner := bufio.NewScanner(file)
for scanner.Scan() {
data := scanner.Bytes()
if bytes.HasPrefix(data, []byte("(")) {
continue
}
line := scanner.Text()
fmt.Println(line)
}
}
输出:
acceptant|1
acceptation|3
accepted|6
accepting|1
按照设计,Go 代码应该是高效的。Go 标准库测试包包含一个基准功能。
避免不必要的转换和分配很重要。例如,将从文件中读取的字节片转换为字符串、分配和复制。
在这种情况下,我们只需要将接受的数据转换为字符串即可。例如,更喜欢字节而不是文本。
$ go test dict_test.go -bench=.
BenchmarkText-4 500 2486306 ns/op 898528 B/op 14170 allocs/op
BenchmarkBytes-4 1000 1489828 ns/op 34080 B/op 609 allocs/op
$
样本基准数据:
KEY: Aback.
SYN: Backwards, rearwards, aft, abaft, astern, behind, back.
ANT: Onwards, forwards, ahead, before, afront, beyond, afore.
=
KEY: Abandon.
SYN: Leave, forsake, desert, renounce, cease, relinquish,
discontinue, castoff, resign, retire, quit, forego, forswear,
depart from, vacate, surrender, abjure, repudiate.
ANT: Pursue, prosecute, undertake, seek, court, cherish, favor,
protect, claim, maintain, defend, advocate, retain, support, uphold,
occupy, haunt, hold, assert, vindicate, keep.
=
dict_test.go:
package main
import (
"bufio"
"bytes"
"fmt"
"io/ioutil"
"os"
"strings"
"testing"
)
func BenchmarkText(b *testing.B) {
b.ReportAllocs()
for N := 0; N < b.N; N++ {
file := bytes.NewReader(benchData)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if !strings.HasPrefix(line, "KEY") {
continue
}
_ = line // process line
}
if err := scanner.Err(); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkBytes(b *testing.B) {
b.ReportAllocs()
for N := 0; N < b.N; N++ {
file := bytes.NewReader(benchData)
scanner := bufio.NewScanner(file)
for scanner.Scan() {
data := scanner.Bytes()
if !bytes.HasPrefix(data, []byte("KEY")) {
continue
}
line := scanner.Text()
_ = line // process line
}
if err := scanner.Err(); err != nil {
b.Fatal(err)
}
}
}
var benchData = func() []byte {
// A Complete Dictionary of Synonyms and Antonyms by Samuel Fallows
// http://www.gutenberg.org/files/51155/51155-0.txt
data, err := ioutil.ReadFile(`/home/peter/dictionary.51155-0.txt`)
if err != nil {
panic(err)
}
return data
}()
TA贡献1834条经验 获得超8个赞
package main
import (
"bufio"
"fmt"
"os"
"strings"
)
func main() {
file, _ := os.Open("dic.dat")
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(line, "(") {
continue
}
fmt.Println(line)
}
}
- 2 回答
- 0 关注
- 133 浏览
添加回答
举报