Time.now vs Time.new in Ruby
2 answers
now
is an alias for new
. There is no difference between them. Jeff's price will get the answer (and his answer is also correct, please vote up his answer if you like it) first, because I wrote and ran this test:
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)
Run the test yourself:
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
+4
source to share