-
Notifications
You must be signed in to change notification settings - Fork 376
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
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.
- Loading branch information
Carlos Contreras
committed
Jun 7, 2017
1 parent
3e74a66
commit f3e8b1c
Showing
2 changed files
with
43 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |