topk_test.go 945 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. package stat
  2. import (
  3. "math/rand"
  4. "testing"
  5. "time"
  6. "github.com/stretchr/testify/assert"
  7. )
  8. const (
  9. numSamples = 10000
  10. topNum = 100
  11. )
  12. var samples []Task
  13. func init() {
  14. for i := 0; i < numSamples; i++ {
  15. task := Task{
  16. Duration: time.Duration(rand.Int63()),
  17. }
  18. samples = append(samples, task)
  19. }
  20. }
  21. func TestTopK(t *testing.T) {
  22. tasks := []Task{
  23. {false, 1, "a"},
  24. {false, 4, "a"},
  25. {false, 2, "a"},
  26. {false, 5, "a"},
  27. {false, 9, "a"},
  28. {false, 10, "a"},
  29. {false, 12, "a"},
  30. {false, 3, "a"},
  31. {false, 6, "a"},
  32. {false, 11, "a"},
  33. {false, 8, "a"},
  34. }
  35. result := topK(tasks, 3)
  36. if len(result) != 3 {
  37. t.Fail()
  38. }
  39. set := make(map[time.Duration]struct{})
  40. for _, each := range result {
  41. set[each.Duration] = struct{}{}
  42. }
  43. for _, v := range []time.Duration{10, 11, 12} {
  44. _, ok := set[v]
  45. assert.True(t, ok)
  46. }
  47. }
  48. func BenchmarkTopkHeap(b *testing.B) {
  49. for i := 0; i < b.N; i++ {
  50. topK(samples, topNum)
  51. }
  52. }