goroutine_test.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package common
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand"
  6. "os"
  7. "sync/atomic"
  8. "testing"
  9. "time"
  10. )
  11. func TestParallelJobRun(t *testing.T) {
  12. fmt.Println(os.Getpid())
  13. start := time.Now()
  14. // 累计计算
  15. totalNum := 100*10000*100 + 15
  16. // 每一个g 计算
  17. eachNum := 100
  18. // 累计睡眠
  19. var sleepNum uint64 = 0
  20. // 结果
  21. result := 0
  22. err := ParallelJobRun(context.Background(), uint64(totalNum), uint64(eachNum), func(ctx context.Context, start, end uint64) (interface{}, error) {
  23. count := 0
  24. for ; start < end; start++ {
  25. count = count + int(start)
  26. }
  27. num := rand.Int31n(5)
  28. atomic.AddUint64(&sleepNum, uint64(num))
  29. time.Sleep(time.Millisecond * time.Duration(num))
  30. return count, nil
  31. }, func(ctx context.Context, data interface{}) error {
  32. cdata := data.(int)
  33. result += cdata
  34. return nil
  35. }, 1000)
  36. if err != nil {
  37. t.Fatal(err)
  38. }
  39. 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())
  40. start = time.Now()
  41. fmt.Printf("check count: %v, spend: %vs\n", count(totalNum), time.Now().Sub(start).Seconds())
  42. time.Sleep(time.Second * 1000000)
  43. }
  44. func count(totalNum int) int {
  45. num := 0
  46. for x := 0; x < totalNum; x++ {
  47. num = num + x
  48. }
  49. return num
  50. }
  51. func TestRunJob(t *testing.T) {
  52. var jobs []func()
  53. for x := 0; x < 12; x++ {
  54. jobs = append(jobs, func() {
  55. fmt.Println("run ", x)
  56. time.Sleep(time.Second * 2)
  57. })
  58. }
  59. //RunJob(jobs, 10)
  60. }