Skip to content

Instantly share code, notes, and snippets.

@ujifgc
Created February 20, 2012 10:22
Show Gist options
  • Save ujifgc/1868681 to your computer and use it in GitHub Desktop.
Save ujifgc/1868681 to your computer and use it in GitHub Desktop.
A benchmark for printing bytes
#!/usr/bin/env ruby
require 'benchmark'
PREFIX = %W(TiB GiB MiB KiB B).freeze
UNITS = %W(B KiB MiB GiB TiB).freeze
def as_size1( s )
s = s.to_f
i = PREFIX.length - 1
while s > 512 && i > 0
s /= 1024
i -= 1
end
((s > 9 || s.modulo(1) < 0.1 ? '%d' : '%.1f') % s) + ' ' + PREFIX[i]
end
def as_size2(s)
s, unit = UNITS.reduce(s.to_f) do |(fsize, _), utype|
fsize > 512 ? [fsize / 1024, utype] : (break [fsize, utype])
end
((s > 9 || s.modulo(1) < 0.1 ? '%d' : '%.1f') % s) + ' ' + unit
end
def as_size3 s
s = s.to_f
if s < 512
i = 0
else
max_exp = UNITS.size - 1
i = ( Math.log( s ) / Math.log( 1024 ) ).round
i = max_exp if i > max_exp
s /= 1024 ** i
end
((s > 9 || s.modulo(1) < 0.1 ? '%d' : '%.1f') % s) + ' ' + UNITS[i]
end
ITERATIONS = 1000000
[200, 300, 400, 500, 600, 700, 800].each do |n|
p "#{as_size1(n)} / #{as_size2(n)} / #{as_size3(n)}"
end
Benchmark.bmbm do |bench|
heading = "split"
bench.report( 'while' ) do
ITERATIONS.times do
sz = rand(500000000000000)
as_size1(sz)
end
end
bench.report( 'reduce' ) do
ITERATIONS.times do
sz = rand(500000000000000)
as_size2(sz)
end
end
bench.report( 'log' ) do
ITERATIONS.times do
sz = rand(500000000000000)
as_size3(sz)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment