Skip to content

Commit

Permalink
Add Base.format_bytes(; binary=false) option (#50572)
Browse files Browse the repository at this point in the history
Add a `binary` keyword argument to `Base.format_bytes` that enables
switching between the default units KiB, MiB, GiB, etc. and kB, MB, GB.
I've wanted this feature multiple times before so I thought I should
just make a PR.

```julia
julia> Base.format_bytes(12345678)
"11.774 MiB"

julia> Base.format_bytes(12345678; binary=false) # with this PR
"12.346 MB"
```
  • Loading branch information
staticfloat authored Jul 23, 2023
2 parents 3d944dd + f74bde8 commit 3c5b3c0
Showing 1 changed file with 6 additions and 4 deletions.
10 changes: 6 additions & 4 deletions base/timing.jl
Original file line number Diff line number Diff line change
Expand Up @@ -128,12 +128,14 @@ function padded_nonzero_print(value, str, always_print = true)
end
end

function format_bytes(bytes) # also used by InteractiveUtils
bytes, mb = prettyprint_getunits(bytes, length(_mem_units), Int64(1024))
function format_bytes(bytes; binary=true) # also used by InteractiveUtils
units = binary ? _mem_units : _cnt_units
factor = binary ? 1024 : 1000
bytes, mb = prettyprint_getunits(bytes, length(units), Int64(factor))
if mb == 1
return string(Int(bytes), " ", _mem_units[mb], bytes==1 ? "" : "s")
return string(Int(bytes), " ", units[mb], bytes==1 ? "" : "s")
else
return string(Ryu.writefixed(Float64(bytes), 3), " ", _mem_units[mb])
return string(Ryu.writefixed(Float64(bytes), 3), binary ? " $(units[mb])" : "$(units[mb])B")
end
end

Expand Down

0 comments on commit 3c5b3c0

Please sign in to comment.