Module: Pakyow::Logger::Timekeeper

Defined in:
lib/pakyow/logger/timekeeper.rb

Overview

Helpers for formatting elapsed time in logs.

Class Method Summary collapse

Class Method Details

.format_elapsed_time(time) ⇒ String

Accepts elapsed time and formats it to be more human-readable.

Examples:

Pakyow::Logger::Timekeeper.format_elapsed_time(60)
=> 1.00m
Pakyow::Logger::Timekeeper.format_elapsed_time(15)
=> 15.00s
Pakyow::Logger::Timekeeper.format_elapsed_time(0.1)
=> 100.00ms
Pakyow::Logger::Timekeeper.format_elapsed_time(0.00001)
=> 10.00μs

Parameters:

  • time (Fixnum, Float)

    the elapsed time (in seconds)

Returns:

  • (String)

    elapsed time, rounded to two decimal places with the proper units



31
32
33
34
35
36
37
38
39
40
41
# File 'lib/pakyow/logger/timekeeper.rb', line 31

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

.format_elapsed_time_in_microseconds(time) ⇒ Object



55
56
57
# File 'lib/pakyow/logger/timekeeper.rb', line 55

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

.format_elapsed_time_in_milliseconds(time) ⇒ Object



51
52
53
# File 'lib/pakyow/logger/timekeeper.rb', line 51

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

.format_elapsed_time_in_minutes(time) ⇒ Object



43
44
45
# File 'lib/pakyow/logger/timekeeper.rb', line 43

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

.format_elapsed_time_in_seconds(time) ⇒ Object



47
48
49
# File 'lib/pakyow/logger/timekeeper.rb', line 47

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

.round_elapsed_time(time) ⇒ Object



59
60
61
# File 'lib/pakyow/logger/timekeeper.rb', line 59

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