Reputation: 6307
I'm looking at creating a randomizing script in Python to execute a loop over a specific amount of time. If I wanted to run a loop 100 times within 5 days at random times within that 5 days, what would be the best way to go about it?
Upvotes: 1
Views: 1358
Reputation: 6156
You could "pre-plan" your randomized times to get the perfect fit in your time range. This assumes your loop time is insignificant in the scale of days (for 100 runs). You would need to add something if you wanted to be really exact
import random, time
def Rand_Run(func, time_range, num_runs):
# time range passed as days / convert to seconds
time_range = time_range*3600*24
# create a list of random numbers and a scaling factor for your time period
r_items = [random.random() for i in xrange(num_runs)]
r_scale = time_range/sum(r_items)
# create the list of time delays between runs
r_time_delays = (r_item*r_scale for r_item in r_items)
# run the function between random time delays
for r_time_delay in r_time_delays:
func()
time.sleep(r_time_delay)
Upvotes: 1
Reputation: 155236
Pick a hundred uniformly distributed random points along the interval and sleep between them:
import random, time
DURATION = 5 * 86400 # five days
EXECS = 100
now = time.time()
points = sorted(random.random() * DURATION + now
for i in xrange(EXECS))
for p in points:
now = time.time()
if p > now:
time.sleep(p - now)
# run your loop here
Upvotes: 4
Reputation: 122
NOT Python, but some idea:
duration = 5*24*60*60 //duration in seconds
for i = 0 to 99
array(i)=rand()*duration
end
sort array
counter=0
while time_elapsed<duration
if (time_elapsed>=array(counter))
DO SOMETHING
counter=counter+1
end
end
Upvotes: 0