为什么Time.zone.parse比DateTime.parse慢得多?

时间:2012-08-24 16:27:14

标签: ruby-on-rails-3 parsing time activesupport

在我的系统(*)上,Time.zone#parse几乎比DateTime#parse慢3.5倍。

由于DateTime.parse已经知道如何处理时区,在什么情况下你想使用Time.zone.parse?

这是基准文件:

module ParseTimeBenchmark
  extend self

  N = 100000
  TS_WO = "2010-01-01 12:03:04"
  TS_W = "2010-01-01 12:03:04 -8:00"

  def string_parser(s) ; s.to_datetime ; end
  def datetime_parser(s) ; DateTime.parse(s) ; end
  def time_zone_parser(s) ; Time.zone.parse(s) ; end

  # sanity check
  if ((s = string_parser(TS_W)) == datetime_parser(TS_W)) && (s == time_zone_parser(TS_W))
    puts("datetimes compare equal")
  else
    puts("warning: datetimes do not compare equal")
  end

  Benchmark.bmbm do |x|
    x.report("string_parser without zone") { N.times { string_parser(TS_WO) }}
    x.report("string_parser with zone") { N.times { string_parser(TS_W) }}
    x.report("datetime_parser without zone") { N.times { datetime_parser(TS_WO) }}
    x.report("datetime_parser with zone") { N.times { datetime_parser(TS_W) }}
    x.report("time_zone_parser without zone") { N.times { time_zone_parser(TS_WO) }}
    x.report("time_zone_parser with zone") { N.times { time_zone_parser(TS_W) }}
  end

end

和结果

>> load '/Users/r/Developer/sketches/parse_time_benchmark.rb'
datetimes compare equal
Rehearsal -----------------------------------------------------------------
string_parser without zone      3.390000   0.030000   3.420000 (  3.412754)
string_parser with zone         4.000000   0.020000   4.020000 (  4.028964)
datetime_parser without zone    2.980000   0.020000   3.000000 (  3.001507)
datetime_parser with zone       3.420000   0.020000   3.440000 (  3.436074)
time_zone_parser without zone   9.050000   0.050000   9.100000 (  9.101839)
time_zone_parser with zone     11.950000   0.050000  12.000000 ( 12.012977)
------------------------------------------------------- total: 34.980000sec

                                    user     system      total        real
string_parser without zone      3.470000   0.020000   3.490000 (  3.495296)
string_parser with zone         4.070000   0.020000   4.090000 (  4.099520)
datetime_parser without zone    3.000000   0.010000   3.010000 (  3.030422)
datetime_parser with zone       3.460000   0.030000   3.490000 (  3.491748)
time_zone_parser without zone   9.190000   0.060000   9.250000 (  9.254589)
time_zone_parser with zone     11.960000   0.050000  12.010000 ( 12.015786)
=> true

(*)我的系统:Ruby 1.9.3(x86_64-darwin10.8.0),Rails 3.2.2,Active Resource 3.2.2

0 个答案:

没有答案