Class: Profiler

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

Defined Under Namespace

Classes: Entry

Constant Summary collapse

@@instance =
nil

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(format = "Program ran in %.3f seconds") ⇒ Profiler

Returns a new instance of Profiler.



11
12
13
# File 'lib/log_and_profile.rb', line 11

def initialize(format = "Program ran in %.3f seconds")
  @current = Entry.new(format)
end

Class Method Details

.enabledObject



20
21
22
# File 'lib/log_and_profile.rb', line 20

def self.enabled
  @@instance ? true : false
end

.enabled=(flag) ⇒ Object



15
16
17
18
# File 'lib/log_and_profile.rb', line 15

def self.enabled=(flag)
  @@instance.dump if @@instance
  @@instance = flag ? Profiler.new : nil
end

.group(group, &block) ⇒ Object



32
33
34
35
36
37
38
# File 'lib/log_and_profile.rb', line 32

def self.group(group, &block)
  if @@instance
    @@instance.profile_group(group, &block)
  else
    block.call
  end
end

.run(action, &block) ⇒ Object



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

def self.run(action, &block)
  if @@instance
    @@instance.profile("#{action} took %.3f seconds", &block)
  else
    block.call
  end
end

Instance Method Details

#dumpObject



55
56
57
# File 'lib/log_and_profile.rb', line 55

def dump
  @current.dump
end

#profile(format) ⇒ Object



40
41
42
43
44
45
46
47
# File 'lib/log_and_profile.rb', line 40

def profile(format)
  parent = @current
  parent.add_child(@current = Entry.new(format))
  res = yield
  @current.finished!
  @current = parent
  res
end

#profile_group(group) ⇒ Object



49
50
51
52
53
# File 'lib/log_and_profile.rb', line 49

def profile_group(group)
  @current.group(group) do
    yield
  end
end