Performance 为什么这个程序在goroutines中表现得不好?

Performance 为什么这个程序在goroutines中表现得不好?,performance,concurrency,grep,go,Performance,Concurrency,Grep,Go,我正在学习围棋编程语言。请考虑以下程序, package main import ( "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

我正在学习围棋编程语言。请考虑以下程序,

package main

import (
    "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.WaitGroup

func main() {
    filepath.Walk("/tmp/", walkFn)
    wg.Wait()
}
该程序遍历
/tmp
目录中的所有文件,并对goroutine中的每个文件执行
grep
。因此,这将生成
n
goroutines,其中
n
/tmp
目录中存在的文件数。Main等待所有goroutine完成工作

有趣的是,这个程序在有goroutine和没有goroutine的情况下执行需要相同的时间。尝试运行
go grep(路径,c)
grep(路径,c)
(执行此操作时需要对频道内容进行注释)


我希望goroutine版本能运行得更快,因为多个grep同时运行。但它几乎在相同的时间内执行。我想知道为什么会发生这种情况?

您的程序的性能与磁盘(或ram,如果/tmp是ram磁盘)的速度有关:计算是。无论有多少个goroutine并行运行,它的读取速度都不会超过这个速度。

尝试使用更多的内核。此外,为了便于比较,请使用更好的根目录,如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

这就是区别。为什么需要显式设置
GOMAXPROCS
?它是否默认为
numpu
()?建议的方法是在启动程序之前设置环境变量GOMAXPROCs,而不是在运行时进行设置。这样,您就可以轻松控制程序的这个特定实例在内核上的消耗量。