Skip to content

Instantly share code, notes, and snippets.

@rsms
Created February 13, 2009 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rsms/62973 to your computer and use it in GitHub Desktop.
Save rsms/62973 to your computer and use it in GitHub Desktop.
'''Time modulus for use with caching etc.
A time window of size window_size second distributed in chunks of granularity seconds.
'''
import time
def modtime(window_size, granularity, t=None):
'''Time distributions
modtime(60, 5)
12 unique evenly distributed over 60 seconds
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11
Or: new token every 5th second within a 60 second rolling window.
0 0 0 0 0 1 1 1 1 1 2 2 2 ... 10 11 11 11 11 11
modtime(30, 3)
10 unique numbers evenly distributed over 30 seconds.
0, 1, 2, 3, 4, 5, 6, 7, 8, 9
Or: new token every 3rd second within a 30 second rolling window.
0 0 0 1 1 1 2 2 2 3 3 3 4 4 4 5 5 5 6 6 6 7 7 7 8 8 8 9 9 9
'''
if t is None:
t = time.time()
t = int(t)
if window_size > 0:
t -= int((t-window_size)/window_size)*window_size
t -= t % granularity
if window_size > 0:
t -= window_size
# simply return t for un-normalized values
# return t
if t:
return t/granularity
return 0
if __name__ == '__main__':
# proof/test
ts = time.time()
for w, g in (
(60, 5),
(30, 3),
(30, 2),
(3600, 60),
):
reg = []
while 1:
start = time.time()
t = modtime(w, g, ts)
if t not in reg:
reg.append(t)
if len(reg) == w/g:
break
ts += 1
print w, g, reg
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment