Last active
April 21, 2021 15:01
-
-
Save ikenna/6422329 to your computer and use it in GitHub Desktop.
Simple Ruby stopwatch
This file contains 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 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 | |
Thank you, love it. I'm a beginner to ruby, I do not understand the line 22 sleep(2)
.
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
I've forked a version using it if you're interested: https://gist.github.com/x4d3/d41e8050caf0f7afbf10e618f64e7a22