学习Ruby中的毫秒

575 阅读1分钟

1.在Ruby中显示时间,精确到毫秒

current_time = Time.now
current_time.strftime('%H:%M:%S.%L')
# => "10:52:07.119"

2.获取以毫秒为单位的当前时间系统

第一种可能性是使用.strftime ,同样。

current_time = Time.now
current_time.strftime('%s%L')
# => "1643017927119"

请注意其结果是一个字符串。

第二种可能性是使用下面的 。

(current_time.to_f * 1000).to_i
# => 1643017927119

结果是一个数字。

3.在Ruby中耗费的时间(以毫秒计

Rails上的Ruby方法

如果你是在Rails环境中,.in_milliseconds 方法已经存在。

# Assuming Rails is loaded
time_a = Time.now
sleep(2)
time_b = Time.now
# Just call .in_milliseconds method
(time_b - time_a).in_milliseconds
# => 2016.464

纯粹的Ruby解决方案

如果你只想知道从Epoch开始所经过的毫秒数,可以输入

DateTime.now.strftime("%Q")
# => "1643018771523"
DateTime.now.strftime("%Q").to_i
# => 1643018771523

但如果你需要两个时间之间的差异,你将不得不写你自己的方法。

def time_difference_in_milliseconds(start, finish)
   (finish - start) * 1000.0
end
time_a = Time.now
sleep(2)
time_b = Time.now

elapsed_time = time_difference_in_milliseconds(time_a, time_b)
# => 2020.874

如果你不介意Monkey Patching,这里有另一种可能性。

class Time
  def to_ms
    (self.to_f * 1000.0).to_i
  end
end

time_a = Time.now
sleep(2)
time_b = Time.now
elapsed_time = time_b.to_ms - time_a.to_ms  
# => 2028

注意事项

虽然我们在网络行业中并不经常需要高精度,但知道这一点总是好的。