class Fluent::NumericTimeParser

to include TimeParseError

def initialize(type, localtime = nil, timezone = nil)

to include TimeParseError
def initialize(type, localtime = nil, timezone = nil)
  @cache1_key = @cache1_time = @cache2_key = @cache2_time = nil
  if type == :unixtime
    define_singleton_method(:parse, method(:parse_unixtime))
    define_singleton_method(:call, method(:parse_unixtime))
  else # :float
    define_singleton_method(:parse, method(:parse_float))
    define_singleton_method(:call, method(:parse_float))
  end
end

def parse_float(value)

# parse_by_to_r (msec): 28.232856 sec
# parse_by_to_r (full): 28.722362 sec
# parse_by_myself(msec): 15.050435 sec
# parse_by_myself(full): 12.162475 sec
10_000_000 times loop on MacBookAir
msec: with 3-digits of msec after dot
full: with 9-digits of nsec after dot
rough benchmark result to compare handmade parser vs Fluent::EventTime.from_time(Time.at(value.to_r))
def parse_float(value)
  unless value.is_a?(String) || value.is_a?(Numeric)
    raise TimeParseError, "value must be a string or a number: #{value}(value.class)"
  end
  if @cache1_key == value
    return @cache1_time
  elsif @cache2_key == value
    return @cache2_time
  end
  begin
    sec_s, nsec_s, _ = value.to_s.split('.', 3) # throw away second-dot and later
    nsec_s = nsec_s && nsec_s[0..9] || '0'
    nsec_s += '0' * (9 - nsec_s.size) if nsec_s.size < 9
    time = Fluent::EventTime.new(sec_s.to_i, nsec_s.to_i)
  rescue => e
    raise TimeParseError, "invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}"
  end
  @cache1_key = @cache2_key
  @cache1_time = @cache2_time
  @cache2_key = value
  @cache2_time = time
  time
end

def parse_unixtime(value)

def parse_unixtime(value)
  unless value.is_a?(String) || value.is_a?(Numeric)
    raise TimeParseError, "value must be a string or a number: #{value}(value.class)"
  end
  if @cache1_key == value
    return @cache1_time
  elsif @cache2_key == value
    return @cache2_time
  end
  begin
    time = Fluent::EventTime.new(value.to_i)
  rescue => e
    raise TimeParseError, "invalid time format: value = #{value}, error_class = #{e.class.name}, error = #{e.message}"
  end
  @cache1_key = @cache2_key
  @cache1_time = @cache2_time
  @cache2_key = value
  @cache2_time = time
  time
end