Created
August 19, 2011 18:53
-
-
Save heycarsten/1157677 to your computer and use it in GitHub Desktop.
Benchmarking creating arrays of time ranges, using Range and a while loop.
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
require 'benchmark' | |
require 'time' | |
SECS_IN_HOUR = 3600 | |
def while_loop | |
now = Time.now | |
ago = now - (SECS_IN_HOUR * 23) | |
max, count, times = now.to_i, ago.to_i, [] | |
begin | |
times << Time.at(count) | |
end while (count += SECS_IN_HOUR) <= max | |
times | |
end | |
def range | |
now = Time.now | |
ago = now - (SECS_IN_HOUR * 23) | |
(ago.to_i..now.to_i).step(SECS_IN_HOUR).map { |s| Time.at(s) } | |
end | |
Benchmark.bmbm do |x| | |
x.report('while_loop') do | |
500_000.times { while_loop } | |
end | |
x.report('range') do | |
500_000.times { range } | |
end | |
end | |
# Rehearsal ---------------------------------------------- | |
# while_loop 7.560000 0.770000 8.330000 ( 8.429125) | |
# range 9.460000 0.570000 10.030000 ( 10.616442) | |
# ------------------------------------ total: 18.360000sec | |
# | |
# user system total real | |
# while_loop 7.490000 0.530000 8.020000 ( 8.134457) | |
# range 9.340000 0.510000 9.850000 ( 9.955324) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment