1

我正在考虑在 Python 中创建一个随机化脚本,以在特定时间内执行一个循环。如果我想在 5 天内随机运行 100 次循环,那么最好的方法是什么?

4

3 回答 3

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
于 2013-01-28T14:42:04.023 回答
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)
于 2013-01-28T14:51:47.870 回答
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
于 2013-01-28T14:41:38.583 回答