@@ -10,25 +10,52 @@ def initialize
10
10
11
11
if defined? ( Process ::CLOCK_MONOTONIC )
12
12
# @!visibility private
13
- def get_time
14
- Process . clock_gettime ( Process ::CLOCK_MONOTONIC )
13
+ def get_time ( unit )
14
+ Process . clock_gettime ( Process ::CLOCK_MONOTONIC , unit )
15
15
end
16
16
elsif Concurrent . on_jruby?
17
17
# @!visibility private
18
- def get_time
19
- java . lang . System . nanoTime ( ) / 1_000_000_000.0
18
+ self ::TIME_UNITS = Hash . new { |_hash , key | raise ArgumentError , "unexpected unit: #{ key } " } . compare_by_identity
19
+ self ::TIME_UNITS . merge! (
20
+ second : 1_000_000_000 ,
21
+ millisecond : 1_000_000 ,
22
+ microsecond : 1_000 ,
23
+ nanosecond : 1 ,
24
+ float_second : 1_000_000_000.0 ,
25
+ float_millisecond : 1_000_000.0 ,
26
+ float_microsecond : 1_000.0 ,
27
+ )
28
+
29
+ # @!visibility private
30
+ def get_time ( unit )
31
+ java . lang . System . nanoTime ( ) / TIME_UNITS [ unit ]
20
32
end
21
33
else
34
+ # @!visibility private
35
+ self ::TIME_UNITS = Hash . new { |_hash , key | raise ArgumentError , "unexpected unit: #{ key } " } . compare_by_identity
36
+ self ::TIME_UNITS . merge! (
37
+ second : [ nil , true ] ,
38
+ millisecond : [ 1_000 , true ] ,
39
+ microsecond : [ 1_000_000 , true ] ,
40
+ nanosecond : [ 1_000_000_000 , true ] ,
41
+ float_second : [ nil , false ] ,
42
+ float_millisecond : [ 1_000.0 , false ] ,
43
+ float_microsecond : [ 1_000_000.0 , false ] ,
44
+ )
22
45
23
46
# @!visibility private
24
- def get_time
47
+ def get_time ( unit )
25
48
synchronize do
26
49
now = Time . now . to_f
27
50
if @last_time < now
28
51
@last_time = now
29
52
else # clock has moved back in time
30
53
@last_time += 0.000_001
31
54
end
55
+ scale , to_int = TIME_UNITS [ unit ]
56
+ now *= scale if scale
57
+ now = now . to_i if to_int
58
+ now
32
59
end
33
60
end
34
61
@@ -46,12 +73,16 @@ def get_time
46
73
#
47
74
# Returns the current time a tracked by the application monotonic clock.
48
75
#
76
+ # @param [Symbol] unit the time unit to be returned, can be either
77
+ # :float_second, :float_millisecond, :float_microsecond, :second,
78
+ # :millisecond, :microsecond, or :nanosecond default to :float_second.
79
+ #
49
80
# @return [Float] The current monotonic time since some unspecified
50
81
# starting point
51
82
#
52
83
# @!macro monotonic_clock_warning
53
- def monotonic_time
54
- GLOBAL_MONOTONIC_CLOCK . get_time
84
+ def monotonic_time ( unit = :float_second )
85
+ GLOBAL_MONOTONIC_CLOCK . get_time ( unit )
55
86
end
56
87
57
88
module_function :monotonic_time
0 commit comments