Class: TestProf::FactoryDefault::Profiler

Inherits:
Object
  • Object
show all
Includes:
Logging
Defined in:
lib/test_prof/factory_default.rb

Constant Summary

Constants included from Logging

Logging::COLORS

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Logging

#log

Constructor Details

#initializeProfiler

Returns a new instance of Profiler.



59
60
61
# File 'lib/test_prof/factory_default.rb', line 59

def initialize
  @data = Hash.new { |h, k| h[k] = {count: 0, time: 0.0} }
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



57
58
59
# File 'lib/test_prof/factory_default.rb', line 57

def data
  @data
end

Instance Method Details

#instrument(name, traits, overrides) ⇒ Object



63
64
65
66
67
68
69
70
71
# File 'lib/test_prof/factory_default.rb', line 63

def instrument(name, traits, overrides)
  start = TestProf.now
  yield.tap do
    time = TestProf.now - start
    key = build_association_name(name, traits, overrides)
    data[key][:count] += 1
    data[key][:time] += time
  end
end


73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/test_prof/factory_default.rb', line 73

def print_report
  if data.empty?
    log :info, "FactoryDefault profiler collected no data"
    return
  end

  # Merge object overrides into one stats record
  data = self.data.each_with_object({}) do |(name, stats), acc|
    name = name.gsub(/\$id\$.+\$di\$/, "<id>")
    if acc.key?(name)
      acc[name][:count] += stats[:count]
      acc[name][:time] += stats[:time]
    else
      acc[name] = stats
    end
  end

  msgs = []

  msgs <<
    "      Factory associations usage:\n    MSG\n\n  first_column = data.keys.map(&:size).max + 2\n\n  msgs << format(\n    \"%\#{first_column}s  %9s  %12s\",\n    \"factory\", \"count\", \"total time\"\n  )\n\n  msgs << \"\"\n\n  total_count = 0\n  total_time = 0.0\n\n  data.to_a.sort_by { |(_, v)| -v[:time] }.each do |(key, factory_stats)|\n    total_count += factory_stats[:count]\n    total_time += factory_stats[:time]\n\n    msgs << format(\n      \"%\#{first_column}s  %9d  %12s\",\n      key, factory_stats[:count], factory_stats[:time].duration\n    )\n  end\n\n  msgs <<\n    <<~MSG\n\n      Total associations created: \#{total_count}\n      Total uniq associations created: \#{data.size}\n      Total time spent: \#{total_time.duration}\n\n    MSG\n\n  log :info, msgs.join(\"\\n\")\nend\n"