Created
December 14, 2013 14:53
-
-
Save cowboy-cod3r/7960151 to your computer and use it in GitHub Desktop.
Ruby: Determine Time Differences
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
#!/opt/apps/ruby/ruby/bin/ruby | |
require 'date' | |
# Hold the time differences to calculate averages | |
time_diffs = [] | |
# Get three time differences | |
1..3.times do | |
initial_time = DateTime.now() | |
sleep 1 | |
final_time = DateTime.now() | |
# Calculate the difference in seconds | |
diff = ((first - second) * 24 * 60 * 60).to_i | |
# Store the differences as an absolute value | |
time_diffs << diff.abs | |
end | |
# =================================================== | |
# Calculate the average, min and max | |
# The inject, min, and max methods come from the | |
# enumerable module which can be implemented on | |
# and class that contains an each method. | |
# The ruby docs actually have a good description of | |
# the inject, min, and max methods if you want to | |
# how they work | |
# =================================================== | |
avg = time_diffs.inject(:+).to_f / time_diffs.size | |
min = avg.min | |
max = avg.max | |
# Display the Results | |
puts "The average time in seconds was '#{avg}'" | |
puts "The max time in seconds was '#{max}'" | |
puts "The min time in seconds was '#{min}'" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment