我正在考虑在Python中创建一个随机化脚本,以便在特定的时间内执行循环。如果我想在5天内在5天内随机播放100次循环,那么最好的方法是什么呢?
答案 0 :(得分:4)
沿着间隔选择一百个均匀分布的随机点并在它们之间休眠:
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
答案 1 :(得分:1)
你可以"预先计划"您的随机时间可以在您的时间范围内完美契合。这假设您的循环时间在天数(100次运行)中无关紧要。如果你想要真正准确的话,你需要添加一些东西
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)
答案 2 :(得分:0)
不是Python,但有些想法:
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