Class: Profilizer::Profiler

Inherits:
Object
  • Object
show all
Defined in:
lib/profilizer/profiler.rb

Instance Method Summary collapse

Instance Method Details

#profile_gc(skip, &block) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/profilizer/profiler.rb', line 42

def profile_gc(skip, &block)
  return block.call if skip

  GC.start
  before = GC.stat(:total_freed_objects)
  result = block.call
  GC.start
  after = GC.stat(:total_freed_objects)

  puts "Objects Freed: #{after - before}"
  result
end

#profile_memory(skip, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
# File 'lib/profilizer/profiler.rb', line 17

def profile_memory(skip, &block)
  return block.call if skip

  memory_usage_before = `ps -o rss= -p #{Process.pid}`.to_i
  result = block.call
  memory_usage_after = `ps -o rss= -p #{Process.pid}`.to_i

  used_memory = ((memory_usage_after - memory_usage_before) / 1024.0).round(2)
  puts "Memory usage: #{used_memory} MB"
  result
end

#profile_method(memory: true, time: true, gc: true) ⇒ Object



7
8
9
10
11
12
13
14
15
# File 'lib/profilizer/profiler.rb', line 7

def profile_method(memory: true, time: true, gc: true)
  profile_memory(!memory) do
    profile_time(!time) do
      profile_gc(!gc) do
        yield
      end
    end
  end
end

#profile_time(skip, &block) ⇒ Object



29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/profilizer/profiler.rb', line 29

def profile_time(skip, &block)
  return block.call if skip

  result = nil

  time_elapsed = Benchmark.realtime do
    result = block.call
  end

  puts "Time: #{time_elapsed.round(2)} seconds"
  result
end