Skip to content

Instantly share code, notes, and snippets.

@heycarsten
Created August 19, 2011 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heycarsten/1157677 to your computer and use it in GitHub Desktop.
Save heycarsten/1157677 to your computer and use it in GitHub Desktop.
Benchmarking creating arrays of time ranges, using Range and a while loop.
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