在crystal lang中减去两次
Subtract two times in crystal lang
我正在为 crystal 编写一个小的基准测试,想比较一下没有任何其他库所花费的时间。
在 ruby 这样的编程语言中,我会这样做:
t = Time.new
sleep 3
puts "Time: #{Time.new - t}s"
有没有办法获取当前的单调时钟时间并从另一个时间中减去它以获得至少小数点后 3 位的精度?
The typical time representation provided by the operating system is
based on a "wall clock" which is subject to changes for clock
synchronization. This can result in discontinuous jumps in the
time-line making it not suitable for accurately measuring elapsed
time.
...
As an alternative, the operating system also provides a monotonic
clock. Its time-line has no specfied starting point but is strictly
linearly increasing.
This monotonic clock should always be used for measuring elapsed time.
A reading from this clock can be taken using .monotonic
:
t1 = Time.monotonic
# operation that takes 1 minute
t2 = Time.monotonic
t2 - t1 # => 1.minute (approximately)
The execution time of a block can be measured using .measure
:
elapsed_time = Time.measure do
# operation that takes 20 milliseconds
end
elapsed_time # => 20.milliseconds (approximately)
* 强调我的。
因此您的示例基本相同,但使用 Time.monotonic
而不是 Time.new
。
我正在为 crystal 编写一个小的基准测试,想比较一下没有任何其他库所花费的时间。
在 ruby 这样的编程语言中,我会这样做:
t = Time.new
sleep 3
puts "Time: #{Time.new - t}s"
有没有办法获取当前的单调时钟时间并从另一个时间中减去它以获得至少小数点后 3 位的精度?
The typical time representation provided by the operating system is based on a "wall clock" which is subject to changes for clock synchronization. This can result in discontinuous jumps in the time-line making it not suitable for accurately measuring elapsed time.
...
As an alternative, the operating system also provides a monotonic clock. Its time-line has no specfied starting point but is strictly linearly increasing.
This monotonic clock should always be used for measuring elapsed time.
A reading from this clock can be taken using
.monotonic
:t1 = Time.monotonic # operation that takes 1 minute t2 = Time.monotonic t2 - t1 # => 1.minute (approximately)
The execution time of a block can be measured using
.measure
:elapsed_time = Time.measure do # operation that takes 20 milliseconds end elapsed_time # => 20.milliseconds (approximately)
* 强调我的。
因此您的示例基本相同,但使用 Time.monotonic
而不是 Time.new
。