Permalink
Browse files

round robin epochs instead of sequential counter

  • Loading branch information...
1 parent f6d90ed commit 5a92823a70b2368043bacc26880f2c22399376da @igrigorik committed May 9, 2010
Showing with 23 additions and 12 deletions.
  1. +16 −5 rrstat.rb
  2. +7 −7 spec/rrstat_spec.rb
View
@@ -4,26 +4,37 @@ class RRStat
def initialize(opts)
@precision = opts[:precision]
@buckets = opts[:buckets]
+ @debug = opts[:debug] || false
@current = nil
+ @signature = nil
+
@db = Redis.new
end
- def time_epoch; Time.now.to_i / @buckets; end
+ def time_epoch; (Time.now.to_i / @precision) % @buckets; end
+ def epochs_ago(set, num)
+ b = time_epoch-num
+ b = (b < 0) ? @buckets + b : b
+
+ "#{set}:#{b}"
+ end
def buckets(set)
- (0...@buckets).inject([]) {|a,v| a.push "#{set}:#{(time_epoch - v)}" }
+ (0...@buckets).inject([]) {|a,v| a.push epochs_ago(set, v) }
end
def epoch(set)
e = time_epoch
+ s = Time.now.to_i / @precision
now = set + ":" + e.to_s
- if now != @current
+ if now != @current and s != @signature
debug [:new_epoch, e]
@current = now
+ @signature = Time.now.to_i / @precision
- clear_bucket("#{set}:#{e - @buckets}")
+ clear_bucket(epochs_ago(set, @buckets))
end
@current
@@ -79,5 +90,5 @@ def clear_bucket(b)
@db.zremrangebyrank(b, 0, 2**32)
end
- def debug(msg); p msg; end
+ def debug(msg); p msg if @debug; end
end
View
@@ -22,7 +22,7 @@
end
it "should increment buckets within correct epoch" do
- rr.epoch("test").should match(/test:210394200/)
+ rr.epoch("test").should match(/test:0/)
rr.incr("test", "key")
rr.score("test", "key").should == 1
@@ -32,15 +32,15 @@
# advance to next epoch
time_travel_to(Time.now + 10) do
- rr.epoch("test").should match(/test:210394201/)
+ rr.epoch("test").should match(/test:1/)
rr.incr("test", "key")
rr.score("test", "key").should == 4
end
# advance 5 epochs, to scroll original incr's off the list
- time_travel_to(Time.now + 40) do
- rr.epoch("test").should match(/test:210394206/)
+ time_travel_to(Time.now + 60) do
+ rr.epoch("test").should match(/test:0/)
rr.incr("test", "key")
rr.score("test", "key").should == 2
@@ -53,7 +53,7 @@
# advance to next epoch
time_travel_to(Time.now + 10) do
- rr.epoch("test").should match(/test:210394201/)
+ rr.epoch("test").should match(/test:1/)
rr.incr("test", "key3", 5)
rr.first("test", 3).should == ["key3", "key2", "key1"]
@@ -67,7 +67,7 @@
# advance to next epoch
time_travel_to(Time.now + 10) do
- rr.epoch("test").should match(/test:210394201/)
+ rr.epoch("test").should match(/test:1/)
rr.incr("test", "key3", 5)
rr.last("test", 3).should == ["key1", "key2", "key3"]
@@ -81,7 +81,7 @@
# advance to next epoch
time_travel_to(Time.now + 10) do
- rr.epoch("test").should match(/test:210394201/)
+ rr.epoch("test").should match(/test:1/)
rr.incr("test", "key")
rr.score("test", "key").should == 2

0 comments on commit 5a92823

Please sign in to comment.