Class: Gitlab::Memory::Instrumentation

Inherits:
Object
  • Object
show all
Defined in:
lib/gitlab/memory/instrumentation.rb

Constant Summary collapse

KEY_MAPPING =
{
  total_allocated_objects: :mem_objects,
  total_malloc_bytes: :mem_bytes,
  total_mallocs: :mem_mallocs
}.freeze
MUTEX =
Mutex.new

Class Method Summary collapse

Class Method Details

.available?Boolean

Returns:

  • (Boolean)

19
20
21
22
# File 'lib/gitlab/memory/instrumentation.rb', line 19

def self.available?
  Thread.respond_to?(:trace_memory_allocations=) &&
    Thread.current.respond_to?(:memory_allocations)
end

.measure_thread_memory_allocations(previous) ⇒ Object

This method returns a hash with the following keys:

  • mem_objects: number of allocated heap slots (as reflected by GC)

  • mem_mallocs: number of malloc calls

  • mem_bytes: number of bytes allocated by malloc for objects that did not fit

    into a heap slot
    
  • mem_total_bytes: number of bytes allocated for both objects consuming an object slot

    and objects that required a malloc (mem_malloc_bytes)
    

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/gitlab/memory/instrumentation.rb', line 43

def self.measure_thread_memory_allocations(previous)
  return unless available?
  return unless previous

  current = Thread.current.memory_allocations
  return unless current

  # calculate difference in a memory allocations
  result = previous.to_h do |key, value|
    [KEY_MAPPING.fetch(key), current[key].to_i - value]
  end

  result[:mem_total_bytes] = result[:mem_bytes] + result[:mem_objects] * GC::INTERNAL_CONSTANTS[:RVALUE_SIZE]

  result
end

.start_thread_memory_allocationsObject


24
25
26
27
28
29
30
31
32
33
34
# File 'lib/gitlab/memory/instrumentation.rb', line 24

def self.start_thread_memory_allocations
  return unless available?

  MUTEX.synchronize do
    # This method changes a global state
    Thread.trace_memory_allocations = true
  end

  # it will return `nil` if disabled
  Thread.current.memory_allocations
end

.with_memory_allocationsObject


60
61
62
63
64
# File 'lib/gitlab/memory/instrumentation.rb', line 60

def self.with_memory_allocations
  previous = self.start_thread_memory_allocations
  yield
  self.measure_thread_memory_allocations(previous)
end