Last active
August 29, 2015 13:57
-
-
Save vrinek/9668596 to your computer and use it in GitHub Desktop.
Dead-simple nested timers for Ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class MyTimerClass | |
attr_reader :timers | |
def initialize | |
@timers = {} | |
@parent_timer = nil | |
end | |
def clock!(name, &block) | |
@timers[name] ||= 0 | |
parent_timer = @parent_timer | |
@parent_timer = name | |
start_time = Time.now | |
result = yield block | |
diff_time = Time.now - start_time | |
@timers[name] += diff_time | |
@timers[parent_timer] -= diff_time if parent_timer | |
@parent_timer = parent_timer | |
result | |
end | |
end | |
$timer = MyTimerClass.new | |
$timer.clock! :main do | |
10.times do | |
$timer.clock! :sleeping do | |
sleep rand | |
end | |
$timer.clock! :eating do | |
print "om " | |
end | |
$timer.clock! :eating do | |
print "nom " | |
end | |
end | |
print "\n" | |
end | |
p $timer.timers |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment