我正在學(xué)習(xí) Go 編程語言。請考慮以下程序,package mainimport ( "fmt" "bytes" "os" "os/exec" "path/filepath" "sync")func grep(file string) { defer wg.Done() cmd := exec.Command("grep", "-H", "--color=always", "add", file) var out bytes.Buffer cmd.Stdout = &out cmd.Run() fmt.Printf("%s\n", out.String())}func walkFn(path string, info os.FileInfo, err error) error { if !info.IsDir() { wg.Add(1) go grep (path) } return nil}var wg sync.WaitGroupfunc main() { filepath.Walk("/tmp/", walkFn) wg.Wait()}該程序遍歷目錄中的所有文件/tmp,并對grepgoroutine 中的每個文件執(zhí)行 a。所以這將產(chǎn)生ngoroutines,其中n是目錄中存在的文件數(shù)/tmp。Main 等待所有 goroutine 完成工作。有趣的是,該程序在使用和不使用 goroutine 的情況下執(zhí)行所需的時間相同。嘗試運行g(shù)o grep (path, c)和grep (path, c)(這樣做時您需要評論頻道內(nèi)容)。我期待 goroutine 版本運行得更快,因為多個 grep 同時運行。但它幾乎在相等的時間內(nèi)執(zhí)行。我想知道為什么會發(fā)生這種情況?
2 回答

墨色風(fēng)雨
TA貢獻1853條經(jīng)驗 獲得超6個贊
嘗試使用更多內(nèi)核。此外,為了比較目的,使用更好的根目錄,如 Go 目錄。SSD 也有很大的不同。例如,
func main() {
runtime.GOMAXPROCS(runtime.NumCPU())
goroot := "/home/peter/go/"
filepath.Walk(goroot, walkFn)
wg.Wait()
fmt.Println("GOMAXPROCS:", runtime.GOMAXPROCS(0))
}
GOMAXPROCS: 1
real 0m10.137s
user 0m2.628s
sys 0m6.472s
GOMAXPROCS: 4
real 0m3.284s
user 0m2.492s
sys 0m5.116s
- 2 回答
- 0 關(guān)注
- 211 瀏覽
添加回答
舉報
0/150
提交
取消