File: human_readable_unit.rb

package info (click to toggle)
ruby-benchmark-memory 0.2.0-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 300 kB
  • sloc: ruby: 1,121; makefile: 7; sh: 4
file content (35 lines) | stat: -rw-r--r-- 747 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# frozen_string_literal: true

require 'delegate'

module Benchmark
  module Memory
    # Transforms raw numbers into a human-readable scale and suffix
    class HumanReadableUnit < SimpleDelegator
      # @return [Integer] the exponential scale of the value
      def scale
        scale = Math.log10(__getobj__)
        scale = 0 if scale.infinite?
        scale = (scale / 3).to_i

        if scale <= 5
          scale
        else
          0
        end
      end

      # @return [String] the single-character unit for the value
      def unit
        case scale
        when 1 then 'k'
        when 2 then 'M'
        when 3 then 'B'
        when 4 then 'T'
        when 5 then 'Q'
        else ' '
        end
      end
    end
  end
end