-
-
Save ikenna/6422329 to your computer and use it in GitHub Desktop.
| 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 | |
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/
I've forked a version using it if you're interested: https://gist.github.com/x4d3/d41e8050caf0f7afbf10e618f64e7a22
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'
Thank you so much!