Skip to content

Instantly share code, notes, and snippets.

@charliepark
Last active September 25, 2015 17:08
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 charliepark/955327 to your computer and use it in GitHub Desktop.
Save charliepark/955327 to your computer and use it in GitHub Desktop.
# NOTE: This is from an older version of Rails / Ruby. The code should still work, but you'll probably find that Date is much faster than Time now.
require 'benchmark'
def bmd
Benchmark.ms { 1000.times { puts Date.today } }
end
def bmt
Benchmark.ms { 1000.times { puts Time.now } }
end
# you'll see that running 'bmt' is much faster than 'bmd'
# so in your views, if you're looking to output some strftime or something similar, use Time.now instead of Date.time
102.461099624634
132.434129714966
104.948043823242
101.39799118042
101.342916488647
100.467920303345
94.0859317779541
116.589069366455
94.5439338684082
97.1629619598389
average: 104.543399810791
bmd:
323.458909988403
259.627103805542
344.912052154541
207.971096038818
193.113088607788
221.312999725342
250.807046890259
230.386018753052
252.316951751709
224.37310218811
average: 250.827836990356
def month_name_d(month = Date.today.month)
Date::MONTHNAMES[month]
end
def month_name_t(month = Time.now.month)
Date::MONTHNAMES[month]
end
ruby-1.8.7-p174 > Benchmark.ms { 1000.times { month_name_d } }
=> 79.9229145050049
ruby-1.8.7-p174 > Benchmark.ms { 1000.times { month_name_d } }
=> 78.8428783416748
ruby-1.8.7-p174 > Benchmark.ms { 1000.times { month_name_d } }
=> 82.1850299835205
ruby-1.8.7-p174 > Benchmark.ms { 1000.times { month_name_t } }
=> 2.17700004577637
ruby-1.8.7-p174 > Benchmark.ms { 1000.times { month_name_t } }
=> 1.98602676391602
ruby-1.8.7-p174 > Benchmark.ms { 1000.times { month_name_t } }
=> 2.27212905883789
also, see http://codelikezell.com/benchmarking-ruby-time-and-date-instantiation/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment