Skip to content

Instantly share code, notes, and snippets.

@warmwaffles
Last active March 29, 2018 21:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save warmwaffles/cde51dbf5eaa130ac03a4e4712162ebb to your computer and use it in GitHub Desktop.
Save warmwaffles/cde51dbf5eaa130ac03a4e4712162ebb to your computer and use it in GitHub Desktop.
Quick stopwatch to do some basic timings in ruby
#
# A simple stop watch for a quick timer to check app performance
#
# @see https://blog.dnsimple.com/2018/03/elapsed-time-with-ruby-the-right-way/
#
# @example Basic Usage
# timer = Stopwatch.new
# timer.start #=> 59539.814152996
# timer.stop #=> 59544.700881683
# timer.elapsed #=> 4.886728687000868
#
class Stopwatch
# Start the stopwatch.
#
# @note this will clear the stopped time
#
# @return [Float] The time started at
def start
@stopped = nil
@started = current_time
end
# Get the time elapsed since start.
#
# @note this does not stop the timer
#
# @return [Float] The time since the timer was started
def lap
current_time - @started
end
# Stops the timer.
#
# @return [Float] The time stopped at
def stop
@stopped = current_time
end
# The amount of time between when the timer started and stopped.
#
# @note if the timer was never started then it will return the lap time
#
# @return [Float]
def elapsed
(@stopped || current_time) - @started
end
# Reset the timer
#
# @return [void]
def reset
@started = nil
@stopped = nil
end
private
def current_time
Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment