Benchmarking Ruby Time and Date instantiation
Posted: 03/28/2009
A comparison of various ways to represent dates and times in ruby. I am creating October 10, 2007 in every case, here are the tests:
n=10000 Benchmark.bm(10) do |test| test.report("Date.strptime: ") do n.times {Date.strptime("20071001","%Y%m%d")} end test.report("Date.parse: ") do n.times {Date.parse("20071001")} end test.report("Time.now: ") do n.times {Time.now} end test.report("Date.new: ") do n.times {Date.new(2007, 10, 1)} end test.report("DateTime.civil: ") do n.times {DateTime.civil(2007, 10, 1)} end test.report("DateTime.parse: ") do n.times {DateTime.parse("20071001")} end test.report("DateTime.strptime: ") do n.times {DateTime.strptime("20071001","%Y%m%d")} end test.report("Time.local: ") do n.times {Time.local(2007, "oct", 1)} end test.report("Time.parse: ") do n.times {Time.parse("20071001")} end test.report("Time.quick_parse: ") do n.times {Time.quick_parse("20071001")} end end
Time.quick_parse is a method that I defined, it’s going to be the fastest way to parse a string in the form “YYYYMMDD”:
class Time class << self # Usage: Time.quick_parse("YYYYMMDD") def quick_parse(date_str) local(date_str[0..3], RFC2822_MONTH_NAME[date_str[4..5].to_i - 1], date_str[6..7]) end end end
The results:
user system total real Date.strptime: 2.890000 0.040000 2.930000 ( 2.982972) Date.parse: 3.630000 0.050000 3.680000 ( 3.755735) Time.now: 0.010000 0.000000 0.010000 ( 0.008608) Date.new: 0.590000 0.010000 0.600000 ( 0.597446) DateTime.civil: 1.640000 0.010000 1.650000 ( 1.675539) DateTime.parse: 4.970000 0.050000 5.020000 ( 5.066107) DateTime.strptime: 4.250000 0.050000 4.300000 ( 4.342663) Time.local: 0.120000 0.000000 0.120000 ( 0.123242) Time.parse: 1.720000 0.010000 1.730000 ( 1.750917) Time.quick_parse: 0.150000 0.000000 0.150000 ( 0.157280)
The version of Ruby that I’m using:
ruby -v ruby 1.8.6 (2008-03-03 patchlevel 114) [universal-darwin9.0]
I'm a skier, web developer, entrepreneur, freelancer, and all around stand-up guy living in Manhattan. This is me, repping one of my favorite shirts...