Joel VanderWerf wrote:
> Oh what the heck, here's the benchmark, and the winner is... strings!
Oops. I got the benchmark labels backwards. Strings are slower. Here's
the correct code and output:
require 'benchmark'
n = 1000000
the_float = 1.0/7
raise unless ("%0.2f" % the_float).to_f == (the_float*100).round/100.0
Benchmark.bmbm(10) do |rpt|
rpt.report("float rounding") do
n.times {
(the_float*100).round/100.0
}
end
rpt.report("string rounding") do
n.times {
("%0.2f" % the_float).to_f
}
end
end
__END__
Output:
Rehearsal ---------------------------------------------------
float rounding 2.210000 0.000000 2.210000 ( 2.884535)
string rounding 3.210000 0.000000 3.210000 ( 6.516337)
------------------------------------------ total: 5.420000sec
user system total real
float rounding 2.190000 0.000000 2.190000 ( 4.398573)
string rounding 3.170000 0.010000 3.180000 ( 6.466687)
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407