File: os_memory_leak_tracker.rb

package info (click to toggle)
ruby-ethon 0.16.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 676 kB
  • sloc: ruby: 5,403; sh: 9; makefile: 8
file content (48 lines) | stat: -rw-r--r-- 1,158 bytes parent folder | download | duplicates (2)
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
45
46
47
48
# frozen_string_literal: true
class OSMemoryLeakTracker
  attr_reader :current_run

  def initialize
    @previous_run = @current_run = 0
  end

  def difference_between_runs(basis=@previous_run)
    @current_run - basis
  end

  def total_difference_between_runs
    difference_between_runs(@initial_count_run)
  end

  def capture_initial_memory_usage
    capture_memory_usage
    @initial_count_run = @current_run
  end

  def capture_memory_usage
    @previous_run = @current_run
    @current_run = rss_bytes
  end

  def dump_status(logger)
    delta = difference_between_runs
    logger.add(log_level(delta), sprintf("\tTotal memory usage (kb): %d (%+d)", current_run, delta))
  end

  private
  # amount of memory the current process "is using", in RAM
  # (doesn't include any swap memory that it may be using, just that in actual RAM)
  # Code loosely based on https://github.com/rdp/os/blob/master/lib/os.rb
  # returns 0 on windows
  def rss_bytes
    if ENV['OS'] == 'Windows_NT'
      0
    else
      `ps -o rss= -p #{Process.pid}`.to_i # in kilobytes
    end
  end

  def log_level(delta)
    delta > 0 ? Logger::WARN : Logger::DEBUG
  end
end