Skip to content

Instantly share code, notes, and snippets.

@jamis
Created June 6, 2011 22:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jamis/1011212 to your computer and use it in GitHub Desktop.
Save jamis/1011212 to your computer and use it in GitHub Desktop.
A simple helper for timing sequences of code.
# Easy to use:
#
# timer = LapTimer.new
# # some task that might take awhile
# timer.mark :step2
# # another task that needs timing
# timer.mark :step3
# # and another task to time
# timer.report
#
# Emits the elapsed (wallclock) time between each of the marked sections,
# including the total elapsed time for the entire block.
class LapTimer
def initialize(name=:start)
@times = []
mark(name)
end
def mark(name)
@times << [name, Time.now]
end
def report
mark :end
total_elapsed = @times.last[1] - @times.first[1]
(@times.length-1).times do |n|
from_name, from_time = @times[n]
to_name, to_time = @times[n+1]
elapsed = to_time - from_time
puts "%5.2fs (%5.1f%%) :: %s" % [elapsed, (elapsed / total_elapsed) * 100, from_name]
end
puts "%5.2fs elapsed time" % total_elapsed
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment