Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add benchmark for format() vs round().to_s #127

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
22 changes: 22 additions & 0 deletions code/general/format-vs-round-and-to-s.rb
Original file line number Diff line number Diff line change
@@ -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