Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env ruby
- require 'date'
- require 'benchmark'
- def weekend_count(start_date, end_date)
- size = (end_date - start_date).to_i
- count = 0
- if start_date.wday != 0
- size -= (7 - start_date.wday).to_i
- count += 1
- end
- left_over = size % 7
- if left_over == 0
- count = (count / 7) * 2
- else
- size -= left_over
- count += (size / 7) * 2 + 1
- end
- count
- end
- def weekend_count_normal(start_date, end_date)
- (start_date..end_date).count{ |d| [0, 6].include?(d.wday) }
- end
- distances = [10, 100, 1000, 10000, 100000]
- today = Date.today
- entries = distances.map { |d| [today - d, today] }
- entries.each do |entry|
- puts "Distance #{(entry[1] - entry[0]).to_i}"
- puts "Optimized result: #{weekend_count(entry[0], entry[1])}"
- puts "Normal result: #{weekend_count_normal(entry[0], entry[1])}"
- Benchmark.bm(100) do |bm|
- bm.report('Optimized') do
- weekend_count(entry[0], entry[1])
- end
- bm.report('Normal') do
- weekend_count_normal(entry[0], entry[1])
- end
- end
- en
Add Comment
Please, Sign In to add comment