Performance 如何将filepath.Walkfunc作为goroutine运行
我正在尝试解析一个大型图像数据集。我正在使用filepath.Walk]并处理在那里找到的每个文件。我想要文件路径Performance 如何将filepath.Walkfunc作为goroutine运行,performance,go,Performance,Go,我正在尝试解析一个大型图像数据集。我正在使用filepath.Walk]并处理在那里找到的每个文件。我想要文件路径 package main import ( "fmt" "image/color" "image/png" "math/rand" "os" ) var ( Black = color.Gray{0} ) func getRandFloatNumber(min, max float32) float32 { return
package main
import (
"fmt"
"image/color"
"image/png"
"math/rand"
"os"
)
var (
Black = color.Gray{0}
)
func getRandFloatNumber(min, max float32) float32 {
return (rand.Float32()*2 - min) * max
}
func openImage(path string, info os.FileInfo, err error) error {
infile, _ := os.Open(path)
defer infile.Close()
img, err := png.Decode(infile)
if err != nil {
return nil
}
array := make([]float32, 128*128)
for y := 0; y < 128; y++ {
for x := 0; x < 128; x++ {
c := color.GrayModel.Convert(img.At(x, y)).(color.Gray)
if c == Black {
array[x*y] = getRandFloatNumber(0.7, 0.95)
} else {
array[x*y] = getRandFloatNumber(0.1, 0.25)
}
}
}
fmt.Println(info.Name())
return nil
}
主程序包
进口(
“fmt”
“图像/颜色”
“图像/png”
“数学/兰德”
“操作系统”
)
变量(
黑色=颜色。灰色{0}
)
func getRandFloatNumber(最小、最大浮动32)浮动32{
返回值(rand.Float32()*2-最小值)*最大值
}
func openImage(路径字符串,info os.FileInfo,err error)错误{
infle,:=os.Open(路径)
延迟填充。关闭()
img,err:=png.Decode(内嵌)
如果错误!=零{
归零
}
数组:=make([]浮点32,128*128)
对于y:=0;y<128;y++{
对于x:=0;x<128;x++{
c:=color.GrayModel.Convert(img.At(x,y))(color.Gray)
如果c==黑色{
数组[x*y]=getRandFloatNumber(0.7,0.95)
}否则{
数组[x*y]=getRandFloatNumber(0.1,0.25)
}
}
}
fmt.Println(info.Name())
归零
}
如何作为一个gorutine运行openImage
?
或者如何优化此代码?您无法获取filepath.Walk以在goroutine中调用您的函数,但您只需在WalkFunc中启动goroutine即可
package main
import (
"os"
"path/filepath"
)
func main() {
filepath.Walk("/my/dir", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
if info.IsDir() {
return nil
}
// Check more criteria if necessary. Also consider limiting the number
// of concurrent goroutines.
go openImage(path, info)
return nil
})
}
func openImage(path string, info os.FileInfo) {
}
转到openImage()