Module: MemoryProfiler::TopN
- Included in:
- StatHash
- Defined in:
- lib/memory_profiler/top_n.rb
Instance Method Summary collapse
-
#top_n(max = 10) ⇒ Object
Efficient mechanism for finding top_n entries in a list optional block can specify custom element and weight.
Instance Method Details
#top_n(max = 10) ⇒ Object
Efficient mechanism for finding top_n entries in a list optional block can specify custom element and weight
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
# File 'lib/memory_profiler/top_n.rb', line 5 def top_n(max = 10) sorted = if block_given? self.map { |row| yield(row) } else self.dup end sorted.compact! sorted.sort! found = [] last = sorted[0] count = 0 lowest_count = 0 sorted << nil sorted.each do |row| current_item, current_count = row unless current_item == last if count > lowest_count found << {data: last, count: count} end if found.length > max found.sort!{|x,y| x[:count] <=> y[:count] } found.delete_at(0) lowest_count = found[0][:count] end count = 0 last = current_item end count += (current_count || 1) unless row.nil? end found .sort!{|x,y| x[:count] <=> y[:count] } .reverse end |