analysor.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package core
  15. import (
  16. "fmt"
  17. "sort"
  18. "time"
  19. "yunion.io/x/log"
  20. "yunion.io/x/onecloud/pkg/scheduler/options"
  21. )
  22. type predicateAnalysor struct {
  23. enable bool
  24. hint string
  25. starts map[string]time.Time
  26. elpased map[string]time.Duration
  27. }
  28. func newPredicateAnalysor(hint string) *predicateAnalysor {
  29. return &predicateAnalysor{
  30. enable: options.Options.EnableAnalysis,
  31. hint: hint,
  32. starts: make(map[string]time.Time),
  33. elpased: make(map[string]time.Duration),
  34. }
  35. }
  36. func (p *predicateAnalysor) Start(pName string) *predicateAnalysor {
  37. if !p.enable {
  38. return p
  39. }
  40. p.starts[pName] = time.Now()
  41. return p
  42. }
  43. func (p *predicateAnalysor) End(pName string, end time.Time) *predicateAnalysor {
  44. if !p.enable {
  45. return p
  46. }
  47. start, ok := p.starts[pName]
  48. if !ok {
  49. panic(fmt.Sprintf("Not found start time of %q", pName))
  50. }
  51. p.elpased[pName] = end.Sub(start)
  52. return p
  53. }
  54. type predicateDuration struct {
  55. name string
  56. duration time.Duration
  57. }
  58. type predicateDurations []*predicateDuration
  59. func (p predicateDurations) Len() int {
  60. return len(p)
  61. }
  62. func (p predicateDurations) Swap(i, j int) {
  63. p[i], p[j] = p[j], p[i]
  64. }
  65. func (p predicateDurations) Less(i, j int) bool {
  66. return p[i].duration > p[j].duration
  67. }
  68. func (p *predicateAnalysor) ShowResult() {
  69. if !p.enable {
  70. return
  71. }
  72. lists := make([]*predicateDuration, 0)
  73. for name, d := range p.elpased {
  74. lists = append(lists, &predicateDuration{
  75. name: name,
  76. duration: d,
  77. })
  78. }
  79. l := predicateDurations(lists)
  80. sort.Sort(l)
  81. log.Infof("=================Start %s Result=================", p.hint)
  82. for _, p := range l {
  83. log.Infof("%s: %s", p.name, p.duration)
  84. }
  85. log.Infof("=================End %s Result=======================", p.hint)
  86. }