main.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "log"
  6. "runtime"
  7. "sync/atomic"
  8. "time"
  9. "github.com/tal-tech/go-zero/core/collection"
  10. )
  11. const interval = time.Minute
  12. var traditional = flag.Bool("traditional", false, "enable traditional mode")
  13. func main() {
  14. flag.Parse()
  15. go func() {
  16. ticker := time.NewTicker(time.Second * 5)
  17. defer ticker.Stop()
  18. for {
  19. select {
  20. case <-ticker.C:
  21. fmt.Printf("goroutines: %d\n", runtime.NumGoroutine())
  22. }
  23. }
  24. }()
  25. if *traditional {
  26. traditionalMode()
  27. } else {
  28. timingWheelMode()
  29. }
  30. }
  31. func timingWheelMode() {
  32. var count uint64
  33. tw, err := collection.NewTimingWheel(time.Second, 600, func(key, value interface{}) {
  34. job(&count)
  35. })
  36. if err != nil {
  37. log.Fatal(err)
  38. }
  39. defer tw.Stop()
  40. for i := 0; ; i++ {
  41. tw.SetTimer(i, i, interval)
  42. time.Sleep(time.Millisecond)
  43. }
  44. }
  45. func traditionalMode() {
  46. var count uint64
  47. for {
  48. go func() {
  49. timer := time.NewTimer(interval)
  50. defer timer.Stop()
  51. select {
  52. case <-timer.C:
  53. job(&count)
  54. }
  55. }()
  56. time.Sleep(time.Millisecond)
  57. }
  58. }
  59. func job(count *uint64) {
  60. v := atomic.AddUint64(count, 1)
  61. if v%1000 == 0 {
  62. fmt.Println(v)
  63. }
  64. }