对于千万级长度的数组单值查找:
序号小的,单线程占明显优势;序号大的,多线程占明显优势。
单线程时间不稳定,多线程时间稳定。
go语言测试代码如下:
package main
import (
"fmt"
"math/rand"
"testing"
"time"
)
const (
ARRLEN = 1000_0000
)
var arr []int
var target int
func init() {
arr = make([]int, ARRLEN)
rand.Seed(time.Now().UnixNano())
for i := 0; i < ARRLEN; i++ {
arr[i] = rand.Intn(10_0000_0000)
}
target = arr[9990001]
fmt.Println("初始化完成")
}
//go test -v -test.run TestMutiThreadsSearch
func TestMutiThreadsSearch(t *testing.T) {
fmt.Println("多线程开始")
now := time.Now()
const MAXGE = 10000
const MAXHANG = 1000
index := -1
chindex := make(chan struct{}, 0)
ch := make(chan struct{}, MAXHANG)
f := func(i int) {
for j := 0; j < MAXGE; j++ {
if target == arr[i*MAXGE+j] {
index = i*MAXGE + j
fmt.Println("找到了-------------------", time.Now().Sub(now))
chindex <- struct{}{}
break
}
}
ch <- struct{}{}
}
for i := 0; i < MAXHANG; i++ {
go f(i)
}
for i := 0; i < MAXHANG; i++ {
select {
case <-chindex: //已经找到了
i = MAXHANG
break
case <-ch:
break
}
}
if index == -1 || index == MAXHANG {
fmt.Println(target, "未找到")
} else {
fmt.Println(target, "已经找到了,序号是:", index)
}
fmt.Println("多线程结束", time.Now().Sub(now))
}
//go test -v -test.run TestSingleThreadToSum
//go test -bench=. -test.run TestSingleThreadToSum
//go test -v -cover -run TestSingleThreadToSum
func TestSingleThreadSearch(t *testing.T) {
fmt.Println("单线程开始")
now := time.Now()
//target := 5
index := -1
for i := 0; i < ARRLEN; i++ {
if target == arr[i] {
index = i
break
}
}
fmt.Println(target, "的序号是:", index)
fmt.Println("单线程结束", time.Now().Sub(now))
}
敲命令go test -v:
当查找序号为0时:
当查找序号为4990001时:
当查找序号为9990001时: