Permalink
Browse files

Remove the need for threads for meters

thanks to the wonderful work in codahale/metrics@c72830f
  • Loading branch information...
eric committed Oct 23, 2012
1 parent eb336ed commit 4097953d2029cab7fd2b58f6e5e8b99ebe245a8f
Showing with 23 additions and 11 deletions.
  1. +23 −11 lib/metriks/meter.rb
View
@@ -4,25 +4,22 @@
module Metriks
class Meter
+ TICK_INTERVAL = 5.0
+
def initialize(averager_klass = Metriks::EWMA)
@count = Atomic.new(0)
- @start_time = Time.now
+ @start_time = Time.now.to_f
+ @last_tick = Atomic.new(@start_time)
@m1_rate = averager_klass.new_m1
@m5_rate = averager_klass.new_m5
@m15_rate = averager_klass.new_m15
-
- @thread = Thread.new do
- loop do
- sleep averager_klass::INTERVAL
- tick
- end
- end
end
def clear
@count.value = 0
- @start_time = Time.now
+ @start_time = Time.now.to_f
+ @last_tick.value = @start_time
@m1_rate.clear
@m5_rate.clear
@m15_rate.clear
@@ -34,7 +31,20 @@ def tick
@m15_rate.tick
end
+ def tick_if_nessesary
+ old_tick = @last_tick.value
+ new_tick = Time.new.to_f
+ age = new_tick - old_tick
+ if age > TICK_INTERVAL && @last_tick.compare_and_swap(old_tick, new_tick)
+ required_ticks = age / TICK_INTERVAL
+ required_ticks.to_i.times do
+ tick
+ end
+ end
+ end
+
def mark(val = 1)
+ tick_if_nessesary
@count.update { |v| v + val }
@m1_rate.update(val)
@m5_rate.update(val)
@@ -46,28 +56,30 @@ def count
end
def one_minute_rate
+ tick_if_nessesary
@m1_rate.rate
end
def five_minute_rate
+ tick_if_nessesary
@m5_rate.rate
end
def fifteen_minute_rate
+ tick_if_nessesary
@m15_rate.rate
end
def mean_rate
if count == 0
return 0.0
else
- elapsed = Time.now - @start_time
+ elapsed = Time.now.to_f - @start_time
count / elapsed
end
end
def stop
- @thread.kill
end
end
end

0 comments on commit 4097953

Please sign in to comment.