Skip to content

Instantly share code, notes, and snippets.

@ikenna
Last active April 21, 2021 15:01
Show Gist options
  • Save ikenna/6422329 to your computer and use it in GitHub Desktop.
Save ikenna/6422329 to your computer and use it in GitHub Desktop.
Simple Ruby stopwatch
class Stopwatch
def initialize()
@start = Time.now
end
def elapsed_time
now = Time.now
elapsed = now - @start
puts 'Started: ' + @start.to_s
puts 'Now: ' + now.to_s
puts 'Elapsed time: ' + elapsed.to_s + ' seconds'
elapsed.to_s
end
end
## Usage
s = Stopwatch.new
sleep(2)
puts s.elapsed_time
## Output
# Started: Tue Sep 03 11:44:48 +0100 2013
# Now: Tue Sep 03 11:44:50 +0100 2013
# Elapsed time: 2.000997 seconds
# 2.000997
@erinql
Copy link

erinql commented Jul 4, 2017

Works like a charm! (I'm running through 'Mazes for Programmers' by Jamis Buck, for some fun today, and wanted to test times of some of the algorithms for solving mazes).

@cassioKenji
Copy link

Thank you!

@MackNcD
Copy link

MackNcD commented Aug 23, 2018

Thank you so much!

@x4d3
Copy link

x4d3 commented Oct 25, 2018

It's very good, however I think you should use Process.clock_gettime(Process::CLOCK_MONOTONIC) instead of Time.now as explaines in:
https://blog.dnsimple.com/2018/03/elapsed-time-with-ruby-the-right-way/

@x4d3
Copy link

x4d3 commented Oct 25, 2018

I've forked a version using it if you're interested: https://gist.github.com/x4d3/d41e8050caf0f7afbf10e618f64e7a22

@153111
Copy link

153111 commented Oct 31, 2018

Thank you, love it. I'm a beginner to ruby, I do not understand the line 22 sleep(2).

@ironmaxx
Copy link

ironmaxx commented Jan 5, 2020

I had to stare at this for, like, 20 minutes before it made sense to me.
The 'sleep(2) really messed with me.

If I understand correctly:
right after 's = Stopwatch.new'
'def initialize()' comes into play where
'@start' is assigned whatever the current time is, via 'Time.now'
'@start' holds that value while,
'sleep(2) elapses 2 seconds, then
'elapsed_time' is called
From there, it's just subtracting the original time stored in @start,
from whatever the current time is, derived from 'now = Time.now'

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment