Skip to content
This repository
Browse code

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
  • Loading branch information...
commit 822c858a1a5cad49274404dbc10b7f8107b06cc3 1 parent 83302a4
Andrew White pixeltrix authored
7 activesupport/lib/active_support/core_ext/date_time/conversions.rb
@@ -80,8 +80,11 @@ def to_i
80 80
81 81 private
82 82
  83 + def offset_in_seconds
  84 + (offset * 86400).to_i
  85 + end
  86 +
83 87 def seconds_since_unix_epoch
84   - seconds_per_day = 86_400
85   - (self - ::DateTime.civil(1970)) * seconds_per_day
  88 + (jd - 2440588) * 86400 - offset_in_seconds + seconds_since_midnight
86 89 end
87 90 end
1  activesupport/test/core_ext/date_time_ext_test.rb
@@ -427,6 +427,7 @@ def test_to_f
427 427
428 428 def test_to_i
429 429 assert_equal 946684800, DateTime.civil(2000).to_i
  430 + assert_equal 946684800, DateTime.civil(1999,12,31,19,0,0,Rational(-5,24)).to_i
430 431 end
431 432
432 433 protected

0 comments on commit 822c858

Please sign in to comment.
Something went wrong with that request. Please try again.