如何在 Ruby 中以毫秒为单位计时?
问题描述:
我想弄清楚特定函数使用了多少毫秒.所以我四处张望,但找不到在 Ruby 中以毫秒精度获取时间的方法.
I'm wishing to figure out how many milliseconds a particular function uses. So I looked high and low, but could not find a way to get the time in Ruby with millisecond precision.
你是怎么做到的?在大多数编程语言中,它就像
How do you do this? In most programming languages its just something like
start = now.milliseconds
myfunction()
end = now.milliseconds
time = end - start
答
您可以使用 ruby 的 Time
类.例如:
You can use ruby's Time
class. For example:
t1 = Time.now
# processing...
t2 = Time.now
delta = t2 - t1 # in seconds
现在,delta
是一个 float
对象,您可以获得该类提供的尽可能细粒度的结果.
Now, delta
is a float
object and you can get as fine grain a result as the class will provide.