From f3e8b1c462ebed4561b3a1c5c17ab5a7e7a9111c Mon Sep 17 00:00:00 2001 From: Carlos Contreras Date: Tue, 6 Jun 2017 20:55:41 -0500 Subject: [PATCH] Add benchmark for format() vs round().to_s This compares two alternatives for starting with a floating point number, transform it into a formatted string with a specific number of digits after the point. --- README.md | 21 +++++++++++++++++++++ code/general/format-vs-round-and-to-s.rb | 22 ++++++++++++++++++++++ 2 files changed, 43 insertions(+) create mode 100644 code/general/format-vs-round-and-to-s.rb diff --git a/README.md b/README.md index fd036e9..7532f09 100644 --- a/README.md +++ b/README.md @@ -268,6 +268,27 @@ Comparison: OpenStruct: 96855.3 i/s - 16.56x slower ``` +##### Kernel#format vs Float#round().to_s [code](code/general/format-vs-round-and-to-s.rb) + +``` +$ ruby -v code/general/format-vs-round-and-t +o-s.rb +ruby 2.3.3p222 (2016-11-21 revision 56859) [x86_64-darwin15] +Warming up -------------------------------------- + Float#round 106.645k i/100ms + Kernel#format 84.304k i/100ms + String#% 78.635k i/100ms +Calculating ------------------------------------- + Float#round 1.570M (± 3.2%) i/s - 7.892M in 5.030672s + Kernel#format 1.144M (± 3.0%) i/s - 5.733M in 5.015621s + String#% 1.047M (± 4.2%) i/s - 5.269M in 5.042970s + +Comparison: + Float#round: 1570411.4 i/s + Kernel#format: 1144036.6 i/s - 1.37x slower + String#%: 1046689.1 i/s - 1.50x slower +``` + ### Array ##### `Array#bsearch` vs `Array#find` [code](code/array/bsearch-vs-find.rb) diff --git a/code/general/format-vs-round-and-to-s.rb b/code/general/format-vs-round-and-to-s.rb new file mode 100644 index 0000000..2556d96 --- /dev/null +++ b/code/general/format-vs-round-and-to-s.rb @@ -0,0 +1,22 @@ +require 'benchmark/ips' + +NUM = 1.12678.freeze + +def fast + NUM.round(2).to_s +end + +def avg + format('%.2f', NUM) +end + +def slow + '%.2f' % NUM +end + +Benchmark.ips do |x| + x.report('Float#round') { fast } + x.report('Kernel#format') { avg } + x.report('String#%') { slow } + x.compare! +end