Last active
February 1, 2018 01:56
-
-
Save fffx/2f6fd2d6a8c48362c3dfab99afc5a441 to your computer and use it in GitHub Desktop.
a optimized way count weekend days
This file contains hidden or 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
#!/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 | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
benchmark result