我正在將文本模式掃描儀從Python3轉(zhuǎn)換為Go1.10,但驚訝的是它實(shí)際上慢了2倍。經(jīng)分析,罪魁禍?zhǔn)自趕trings.Contains()。請(qǐng)參閱下面的簡(jiǎn)單基準(zhǔn)。我有什么想念的嗎?您能推薦一種更快的Go模式搜索算法,這種算法在這種情況下會(huì)更好嗎?我不必?fù)?dān)心啟動(dòng)時(shí)間,相同的模式將用于掃描數(shù)百萬個(gè)文件。Py3基準(zhǔn):import timeimport reRUNS = 10000if __name__ == '__main__': with open('data.php') as fh: testString = fh.read() def do(): return "576ad4f370014dfb1d0f17b0e6855f22" in testString start = time.time() for i in range(RUNS): _ = do() duration = time.time() - start print("Python: %.2fs" % duration)Go1.10基準(zhǔn)測(cè)試:package mainimport ( "fmt" "io/ioutil" "log" "strings" "time")const ( runs = 10000)func main() { fname := "data.php" testdata := readFile(fname) needle := "576ad4f370014dfb1d0f17b0e6855f22" start := time.Now() for i := 0; i < runs; i++ { _ = strings.Contains(testdata, needle) } duration := time.Now().Sub(start) fmt.Printf("Go: %.2fs\n", duration.Seconds())}func readFile(fname string) string { data, err := ioutil.ReadFile(fname) if err != nil { log.Fatal(err) } return string(data)}data.php是528KB的文件,可以在這里找到。輸出:Go: 1.98sPython: 0.84s
- 2 回答
- 0 關(guān)注
- 278 瀏覽
添加回答
舉報(bào)
0/150
提交
取消