1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00

Improve performance of DateTime#seconds_since_unix_epoch

Calculate the seconds since the UNIX epoch using the difference in
Julian day numbers from the epoch date. By reducing the Rational math
to just the offset component this gives a significant improvement.

Benchmark:

Calculating --------------------------------------------
       new     27733 i/100ms
   current     15031 i/100ms
       new     27737 i/100ms
   current     15549 i/100ms
--------------------------------------------------------
       new   548182.1 (±0.9%) i/s - 2745567 in 5.008943s
   current   216380.9 (±1.6%) i/s - 1082232 in 5.002781s
       new   510281.9 (±1.2%) i/s - 2551804 in 5.001525s
   current   219858.3 (±1.8%) i/s - 1103979 in 5.023039s
This commit is contained in:
Andrew White 2012-07-02 07:05:17 +01:00
parent 83302a4c13
commit 822c858a1a
2 changed files with 6 additions and 2 deletions

View file

@ -80,8 +80,11 @@ class DateTime
private
def offset_in_seconds
(offset * 86400).to_i
end
def seconds_since_unix_epoch
seconds_per_day = 86_400
(self - ::DateTime.civil(1970)) * seconds_per_day
(jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight
end
end

View file

@ -427,6 +427,7 @@ class DateTimeExtCalculationsTest < ActiveSupport::TestCase
def test_to_i
assert_equal 946684800, DateTime.civil(2000).to_i
assert_equal 946684800, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_i
end
protected