用水晶郎减去两次

时间:2020-10-24 10:45:34

标签: crystal-lang

我正在为Crystal编写一个小型基准,并希望比较没有其他任何库所花费的时间。

在像ruby这样的编程语言中,我会这样做:

t = Time.new
sleep 3
puts "Time: #{Time.new - t}s"

有没有一种方法可以获取当前的单调时钟时间并将其从另一个时间中减去,以使精度至少达到小数点后3位?

1 个答案:

答案 0 :(得分:2)

操作系统提供的典型时间表示为 基于“挂钟”,时钟可能会有所变化 同步。这可能会导致不连续的跳跃 时间线使其不适合准确测量经过时间 时间。

...

作为替代方案,操作系统还提供了单调性 时钟。它的时间表没有指定起点,但严格 线性增加。

单调时钟应始终用于测量经过时间

可以使用.monotonic来获取此时钟的读数:

t1 = Time.monotonic
# operation that takes 1 minute
t2 = Time.monotonic
t2 - t1 # => 1.minute (approximately)

可以使用.measure测量块的执行时间:

elapsed_time = Time.measure do
  # operation that takes 20 milliseconds
end
elapsed_time # => 20.milliseconds (approximately)

-Time - github.com/crystal-lang/crystal

*强调我的。

因此您的示例基本上是相同的,但是使用Time.monotonic而不是Time.new

相关问题