Class: Fiddlesticks::Core

Inherits:
Object
  • Object
show all
Includes:
Memory, OS
Defined in:
lib/fiddlesticks/core.rb

Instance Method Summary collapse

Methods included from Memory

#calculate_memory, #get_memory, #total_memory

Methods included from OS

linux?, mac?, unix?, windows?

Constructor Details

#initialize(total_memory: :gb, used_memory: :mb, gc_enabled: true) ⇒ Core

Returns a new instance of Core.



14
15
16
17
18
19
20
21
# File 'lib/fiddlesticks/core.rb', line 14

def initialize(total_memory: :gb, used_memory: :mb, gc_enabled: true)
  @config = {
    total_memory: total_memory,
    used_memory: used_memory,
    gc_enabled: gc_enabled
  }
  @valid_keys = @config.keys
end

Instance Method Details

#configure(opt = {}) ⇒ Object



23
24
25
26
27
28
29
30
# File 'lib/fiddlesticks/core.rb', line 23

def configure(opt = {})
  #@params opt [Hash]
  #@description Accepts a [Hash] with the keys:
  #   total_memory [Symbol] format type ':kb', ':mb', 'gb' standard: ':gb',
  #   used_memory [Symbol] format type ':kb', ':mb', 'gb' standard: ':mb',
  #   gc_enabled [Boolean] format type 'true', 'false' standard: 'true'
  opt.each { |k, v| @config[k.to_sym] = v if @valid_keys.include? k.to_sym }
end

#measure(&block) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/fiddlesticks/core.rb', line 32

def measure(&block)
  total_memory_type = @config.fetch(:total_memory)
  used_memory_type  = @config.fetch(:used_memory)
  gc_enabled   = @config.fetch(:gc_enabled)

  gc_enabled ? GC.start : GC.disable
  memory_before = get_memory(used_memory_type)
  gc_stat_before  = GC.stat

  time = Benchmark.realtime do
    yield
  end

  if gc_enabled
    GC.start(full_mark: true, immediate_sweep: true, immediate_mark: false)
  end

  gc_stat_after = GC.stat
  memory_after  = get_memory(used_memory_type)
  memory_total = total_memory(total_memory_type)
  memory_used = calculate_memory(memory_before, memory_after, used_memory_type)

  gc = gc_enabled ? "enabled" : "disabled"

  gc_count = gc_stat_after[:count] - gc_stat_before[:count]


  header = ["Ruby Version", "GC", "GC Sweeps", "Total Memory", "Memory Used", "Time"]
  data   = [ RUBY_VERSION, gc, gc_count, memory_total, memory_used, "#{time.round(2)} Seconds"]

  Console.display_table([header, data], width: 100, col_sep: "|", row_sep: "-")
end