Sha256: 0e27181167641d109878158aed88260ee621310dc85369a53fc79bbd0ca63015

Contents?: true

Size: 1.7 KB

Versions: 12

Compression:

Stored size: 1.7 KB

Contents

# frozen_string_literal: true

module Pakyow
  class Logger
    # Helpers for formatting elapsed time in logs.
    #
    module Timekeeper
      # Accepts elapsed time and formats it to be more human-readable.
      #
      # @example
      #   Pakyow::Logger::Timekeeper.format_elapsed_time(60)
      #   => 1.00m
      #
      # @example
      #   Pakyow::Logger::Timekeeper.format_elapsed_time(15)
      #   => 15.00s
      #
      # @example
      #   Pakyow::Logger::Timekeeper.format_elapsed_time(0.1)
      #   => 100.00ms
      #
      # @example
      #   Pakyow::Logger::Timekeeper.format_elapsed_time(0.00001)
      #   => 10.00μs
      #
      # @param time [Fixnum, Float] the elapsed time (in seconds)
      #
      # @return [String] elapsed time, rounded to two decimal places
      #   with the proper units
      #
      def self.format_elapsed_time(time)
        if time >= 60
          format_elapsed_time_in_minutes(time)
        elsif time >= 1
          format_elapsed_time_in_seconds(time)
        elsif time >= 0.001
          format_elapsed_time_in_milliseconds(time)
        else
          format_elapsed_time_in_microseconds(time)
        end
      end

      def self.format_elapsed_time_in_minutes(time)
        round_elapsed_time(time / 60).to_s << "m "
      end

      def self.format_elapsed_time_in_seconds(time)
        round_elapsed_time(time).to_s << "s "
      end

      def self.format_elapsed_time_in_milliseconds(time)
        round_elapsed_time(time * 1_000).to_s << "ms"
      end

      def self.format_elapsed_time_in_microseconds(time)
        round_elapsed_time(time * 1_000_000).to_s << "μs"
      end

      def self.round_elapsed_time(time)
        "%.2f" % time
      end
    end
  end
end

Version data entries

12 entries across 12 versions & 1 rubygems

Version Path
pakyow-core-1.0.6 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.5 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.4 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.3 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.2 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.1 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.0 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.0.rc5 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.0.rc4 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.0.rc3 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.0.rc2 lib/pakyow/logger/timekeeper.rb
pakyow-core-1.0.0.rc1 lib/pakyow/logger/timekeeper.rb