Created
August 8, 2013 19:45
-
-
Save matomesc/6188023 to your computer and use it in GitHub Desktop.
Buckets items by timestamp and counts the items in each bucket
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Buckets(object): | |
""" | |
Buckets items by timestamp and counts the items in each bucket. | |
""" | |
def __init__(self, since, interval=300): | |
""" | |
:param since: Starting timestamp in seconds. | |
:type since: int | |
:param interval: The bucket size in seconds. | |
:type interval: int | |
""" | |
self.ranges = [] | |
self.map = {} | |
self.since = since | |
self.now = int(time.time()) | |
self.interval = 300 | |
# initialize buckets | |
current = since + interval | |
while current < self.now: | |
self.ranges.append(current) | |
current += interval | |
# the first bucket | |
self.map[str(since) + '-' + str(self.ranges[0])] = 0 | |
# the last bucket | |
self.map[str(self.ranges[-1]) + '-' + str(self.now)] = 0 | |
# the rest of the buckets | |
for i in range(1, len(self.ranges)): | |
prev = i - 1 | |
self.map[str(self.ranges[prev]) + '-' + str(self.ranges[i])] = 0 | |
self.sortedMap = sorted(self.map) | |
def add(self, timestamp): | |
""" | |
Add another item to the buckets. The ``time`` parameter is used to | |
determine which bucket to place the item into. | |
:param timestamp: Item timestamp | |
:type timestamp: int | |
""" | |
# determine which bucket to place the item in | |
bucket = None | |
for i in range(len(self.ranges)): | |
if timestamp < self.ranges[i]: | |
bucket = self.sortedMap[i] | |
break | |
# we're not smaller than any range - should go in the last bucket | |
if bucket is None: | |
bucket = self.sortedMap[-1] | |
self.map[bucket] += 1 | |
def distribution(self): | |
return self.map |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment