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

Conversation

carlos-contreras
Copy link

@carlos-contreras carlos-contreras commented Jun 7, 2017

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.

@Arcovion
Copy link
Collaborator

Arcovion commented Jun 7, 2017

Typo: format('%.2f' % NUM)format('%.2f', NUM) or '%.2f' % NUM

@Arcovion
Copy link
Collaborator

Arcovion commented Jun 7, 2017

Strangely, on my machine format is consistently faster than %:

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
Warming up --------------------------------------
         Float#round   128.526k i/100ms
       Kernel#format    96.841k i/100ms
            String#%    89.243k i/100ms
Calculating -------------------------------------
         Float#round      1.981M (± 0.3%) i/s -     10.025M in   5.061882s
       Kernel#format      1.505M (± 0.3%) i/s -      7.554M in   5.017527s
            String#%      1.241M (± 0.3%) i/s -      6.247M in   5.034723s

Comparison:
         Float#round:  1980506.7 i/s
       Kernel#format:  1505458.6 i/s - 1.32x  slower
            String#%:  1240793.9 i/s - 1.60x  slower

So might be worth including both in the benchmark

@carlos-contreras carlos-contreras force-pushed the format-vs-round-and-to-s branch 2 times, most recently from a0cdd3a to 59ca0b8 Compare June 7, 2017 13:41
@carlos-contreras
Copy link
Author

Thanks for the feedback @Arcovion, I updated the PR 👍

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.
@Arcovion Arcovion merged commit 279401e into fastruby:master Jun 7, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

2 participants