File: top_n.rb

package info (click to toggle)
ruby-memory-profiler 1.1.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 284 kB
  • sloc: ruby: 1,128; makefile: 4
file content (44 lines) | stat: -rw-r--r-- 1,192 bytes parent folder | download
1
2
3
4
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
# frozen_string_literal: true

module MemoryProfiler
  module TopN
    # Fast approach for determining the top_n entries in a Hash of Stat objects.
    # Returns results for both memory (memsize summed) and objects allocated (count) as a tuple.
    def top_n(max, metric_method)
      [
        top_n_memory(max, metric_method),
        top_n_objects(max, metric_method)
      ]
    end

    def top_n_memory(max, metric_method)
      metric_memsize = Hash.new(0)

      each_value do |value|
        metric = value.send(metric_method)
        metric_memsize[metric] += value.memsize
      end

      metric_memsize
        .to_a
        .sort_by! { |metric, memsize| [-memsize, metric] }
        .take(max)
        .map! { |metric, memsize| { data: metric, count: memsize } }
    end

    def top_n_objects(max, metric_method)
      metric_objects_count = Hash.new(0)

      each_value do |value|
        metric = value.send(metric_method)
        metric_objects_count[metric] += 1
      end

      metric_objects_count
        .to_a
        .sort_by! { |metric, count| [-count, metric] }
        .take(max)
        .map! { |metric, count| { data: metric, count: count } }
    end
  end
end