Skip to content

Instantly share code, notes, and snippets.

@jish
Created December 14, 2009 00:04
Show Gist options
  • Save jish/255682 to your computer and use it in GitHub Desktop.
Save jish/255682 to your computer and use it in GitHub Desktop.
require 'benchmark'
# This takes like forever because '+=' adds seconds, not days.
bm = Benchmark.measure do
next_meeting = Time.now.next_month.beginning_of_month
while next_meeting.strftime("%a") != "Thu"
next_meeting += 1
end
end
bm.real
# => 2.02875781059265
# => 2.02947306632996
# This is what we want to use, 'advance'
bm = Benchmark.measure do
next_meeting = Time.now.next_month.beginning_of_month
while next_meeting.strftime("%a") != "Thu"
next_meeting = next_meeting.advance(:days => 1)
end
end
bm.real
# => 0.00124406814575195
# => 0.00165700912475586
# While we're at it, we can skip the loop
bm = Benchmark.measure do
next_meeting = Time.now.next_month.beginning_of_month
index = Time::RFC2822_DAY_NAME.index(next_meeting.strftime("%a"))
advance = (4 - index) % 7
next_meeting = next_meeting.advance(:days => advance)
end
bm.real
# => 0.000564098358154297
# => 0.000573873519897461
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment