Time.now
和Time.new
之间是否有区别(没有参数)?可能是内存管理方面的差异还是一些小细节?
答案 0 :(得分:10)
没有区别。
Time.now是:: new的别名。返回初始化为的Time对象 当前的系统时间。
答案 1 :(得分:5)
now
是new
的别名。它们之间没有区别。杰夫的价格得到回答(他的回答也是正确的,如果你愿意的话请投票给他答案)首先,因为我正在编写并运行这个基准:
Ruby 2.1.2 (MRI):
Rehearsal ----------------------------------------------------------------------------
Time.new 0.670000 0.000000 0.670000 ( 0.679709)
Time.now 0.880000 0.010000 0.890000 ( 0.881899)
------------------------------------------------------------------- total: 1.560000sec
user system total real
Time.new 0.720000 0.000000 0.720000 ( 0.719453)
Time.now 0.740000 0.010000 0.750000 ( 0.742711)
Rehearsal ----------------------------------------------------------------------------
Time.new 0.810000 0.000000 0.810000 ( 0.811874)
Time.now 0.830000 0.000000 0.830000 ( 0.831346)
------------------------------------------------------------------- total: 1.640000sec
user system total real
Time.new 0.790000 0.010000 0.800000 ( 0.800082)
Time.now 0.740000 0.000000 0.740000 ( 0.749995)
Rehearsal ----------------------------------------------------------------------------
Time.new 0.680000 0.010000 0.690000 ( 0.690337)
Time.now 0.850000 0.000000 0.850000 ( 0.856800)
------------------------------------------------------------------- total: 1.540000sec
user system total real
Time.new 0.790000 0.010000 0.800000 ( 0.792666)
Time.now 0.770000 0.000000 0.770000 ( 0.777414)
Rehearsal ----------------------------------------------------------------------------
Time.new 0.590000 0.010000 0.600000 ( 0.594650)
Time.now 0.710000 0.010000 0.720000 ( 0.717067)
------------------------------------------------------------------- total: 1.320000sec
user system total real
Time.new 0.870000 0.000000 0.870000 ( 0.872646)
Time.now 0.680000 0.010000 0.690000 ( 0.687092)
Rehearsal ----------------------------------------------------------------------------
Time.new 0.780000 0.010000 0.790000 ( 0.786419)
Time.now 0.780000 0.000000 0.780000 ( 0.789049)
------------------------------------------------------------------- total: 1.570000sec
user system total real
Time.new 0.760000 0.010000 0.770000 ( 0.768194)
Time.now 0.790000 0.010000 0.800000 ( 0.790981)
自己运行基准:
n = 1000000
5.times do
Benchmark.bmbm(40) do |x|
x.report("Time.new"){ n.times { Time.new } }
x.report("Time.now"){ n.times { Time.now } }
end
end
答案 2 :(得分:1)
使用Ruby 2.4.1和Rails 5.0.3 在测试中使用travel_to时,Time.new不会受到它的影响,但是Time.now确实会因此而改变