Iva*_*van 6 performance complexity-theory go
正如您在下面的pprof输出中看到的,我有这些嵌套的for循环,它占用了我程序的大部分时间.源代码是golang,但代码解释如下:
8.55mins 1.18hrs 20: for k := range mapSource {
4.41mins 1.20hrs 21: if positions, found := mapTarget[k]; found {
. . 22: // save all matches
1.05mins 1.05mins 23: for _, targetPos := range positions {
2.25mins 2.33mins 24: for _, sourcePos := range mapSource[k] {
1.28s 15.78s 25: matches = append(matches, match{int32(targetPos), int32(sourcePos)})
. . 26: }
. . 27: }
. . 28: }
. . 29: }
Run Code Online (Sandbox Code Playgroud)
目前我正在使用的结构是2 map[int32][]int32,targetMap和sourceMap.
对于给定的键,这些映射包含一组int.现在我想在两个映射中找到匹配的键,并保存数组中元素的组合.
例如:
sourceMap[1] = [3,4]
sourceMap[5] = [9,10]
targetMap[1] = [1,2,3]
targetMap[2] = [2,3]
targetMap[3] = [1,2]
Run Code Online (Sandbox Code Playgroud)
唯一的共同点是1,结果将是[(3,1), (3,2), (3,3), (4,1), (4,2), (4,3)]
有没有可能的方法(更合适的数据结构或其他)可以提高我的程序的速度?
在我的例子中,地图可以包含1000到150000个键,而内部的数组通常很小.
编辑:并发不是一个选项,因为它已经在几个线程中同时运行了几次.
我可以进一步优化它以便它运行得更快吗?
有没有可能的方法(更合适的数据结构或其他)可以提高我的程序的速度?
大概.
该XY问题是问你尝试的解决方案,而不是你的实际问题.这会导致大量浪费的时间和精力,无论是寻求帮助的人还是提供帮助的人.
我们甚至没有关于您的问题的最基本信息,原始输入数据的形式,内容和频率的描述,以及您想要的输出.什么原始数据应该推动基准测试?
我创建了一些虚构的原始数据,产生了一些虚构的输出和结果:
BenchmarkPeterSO-4 30 44089894 ns/op 5776666 B/op 31 allocs/op
BenchmarkIvan-4 10 152300554 ns/op 26023924 B/op 6022 allocs/op
Run Code Online (Sandbox Code Playgroud)
您的算法可能很慢.
我可能会这样做,这样我就可以同时完成一些工作:
https://play.golang.org/p/JHAmPRh7jr
package main
import (
"fmt"
"sync"
)
var final [][]int32
var wg sync.WaitGroup
var receiver chan []int32
func main() {
final = [][]int32{}
mapTarget := make(map[int32][]int32)
mapSource := make(map[int32][]int32)
mapSource[1] = []int32{3, 4}
mapSource[5] = []int32{9, 10}
mapTarget[1] = []int32{1, 2, 3}
mapTarget[2] = []int32{2, 3}
mapTarget[3] = []int32{1, 2}
wg = sync.WaitGroup{}
receiver = make(chan []int32)
go func() {
for elem := range receiver {
final = append(final, elem)
wg.Done()
}
}()
for k := range mapSource {
if _, ok := mapTarget[k]; ok {
wg.Add(1)
go permutate(mapSource[k], mapTarget[k])
}
}
wg.Wait()
fmt.Println(final)
}
func permutate(a, b []int32) {
for i := 0; i < len(a); i++ {
for j := 0; j < len(b); j++ {
wg.Add(1)
receiver <- []int32{a[i], b[j]}
}
}
wg.Done()
}
Run Code Online (Sandbox Code Playgroud)
您甚至可能想看看您是否从中受益:
for k := range mapSource {
wg.Add(1)
go func(k int32) {
if _, ok := mapTarget[k]; ok {
wg.Add(1)
go permutate(mapSource[k], mapTarget[k])
}
wg.Done()
}(k)
}
Run Code Online (Sandbox Code Playgroud)