File: clock.rb

package info (click to toggle)
ruby-console 1.34.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 272 kB
  • sloc: ruby: 1,509; makefile: 4
file content (40 lines) | stat: -rw-r--r-- 852 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
36
37
38
39
40
# frozen_string_literal: true

# Released under the MIT License.
# Copyright, 2021-2025, by Samuel Williams.

module Console
	# A simple clock utility for tracking and formatting time.
	module Clock
		# Format a duration in seconds as a human readable string.
		#
		# @parameter duration [Numeric] The duration in seconds.
		# @returns [String] The formatted duration.
		def self.formatted_duration(duration)
			if duration < 60.0
				return "#{duration.round(2)}s"
			end
			
			duration /= 60.0
			
			if duration < 60.0
				return "#{duration.floor}m"
			end
			
			duration /= 60.0
			
			if duration < 24.0
				return "#{duration.floor}h"
			end
			
			duration /= 24.0
			
			return "#{duration.floor}d"
		end
		
		# @returns [Time] The current monotonic time.
		def self.now
			::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
		end
	end
end