Permalink
Browse files

Use strftime to convert DateTime to numeric

The native implementation of the seconds since the UNIX epoch in
strftime is significantly faster than our method.

Benchmark:
----------
require 'benchmark/ips'
require 'date'
require 'time'

date = DateTime.civil(1253,7,6,20,4,0)

Benchmark.ips do |x|
  x.report("strftime.to_i") { date.strftime('%s').to_i }
  x.report("ssue.to_i") { ((date - DateTime.civil(1970)) * 86400).to_i }

  x.report("strftime.to_f") { date.strftime('%s').to_f }
  x.report("ssue.to_f") { ((date - DateTime.civil(1970)) * 86400).to_f }
end

Output:
-------
Calculating -------------------------------------
       strftime.to_i     26480 i/100ms
           ssue.to_i     13818 i/100ms
       strftime.to_f     26561 i/100ms
           ssue.to_f     14479 i/100ms
-------------------------------------------------
       strftime.to_i   616937.3 (±2.4%) i/s - 3098160 in 5.024749s
           ssue.to_i   200108.8 (±6.9%) i/s -  994896 in 4.999278s
       strftime.to_f   553581.3 (±2.2%) i/s - 2788905 in 5.040397s
           ssue.to_f   204260.3 (±4.3%) i/s - 1028009 in 5.043072s
  • Loading branch information...
1 parent ab72040 commit 210cd756a628cc19c0d6e44bee8c33dfb2d9d598 @pixeltrix pixeltrix committed Jul 1, 2012
Showing with 1 addition and 2 deletions.
  1. +1 −2 activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -95,7 +95,6 @@ def to_i
private
def seconds_since_unix_epoch
- seconds_per_day = 86_400
- (self - ::DateTime.civil(1970)) * seconds_per_day
+ strftime('%s')
end
end

0 comments on commit 210cd75

Please sign in to comment.