package common import ( "context" "fmt" "math/rand" "os" "sync/atomic" "testing" "time" ) func TestParallelJobRun(t *testing.T) { fmt.Println(os.Getpid()) start := time.Now() // 累计计算 totalNum := 100*10000*100 + 15 // 每一个g 计算 eachNum := 100 // 累计睡眠 var sleepNum uint64 = 0 // 结果 result := 0 err := ParallelJobRun(context.Background(), uint64(totalNum), uint64(eachNum), func(ctx context.Context, start, end uint64) (interface{}, error) { count := 0 for ; start < end; start++ { count = count + int(start) } num := rand.Int31n(5) atomic.AddUint64(&sleepNum, uint64(num)) time.Sleep(time.Millisecond * time.Duration(num)) return count, nil }, func(ctx context.Context, data interface{}) error { cdata := data.(int) result += cdata return nil }, 1000) if err != nil { t.Fatal(err) } fmt.Printf("fork-join count: %v,total_sleep_time: %vs,节省时间: %vs , spend : %vs\n", result, sleepNum/1000, float64(sleepNum/1000)-time.Now().Sub(start).Seconds(), time.Now().Sub(start).Seconds()) start = time.Now() fmt.Printf("check count: %v, spend: %vs\n", count(totalNum), time.Now().Sub(start).Seconds()) time.Sleep(time.Second * 1000000) } func count(totalNum int) int { num := 0 for x := 0; x < totalNum; x++ { num = num + x } return num } func TestRunJob(t *testing.T) { var jobs []func() for x := 0; x < 12; x++ { jobs = append(jobs, func() { fmt.Println("run ", x) time.Sleep(time.Second * 2) }) } //RunJob(jobs, 10) }