dongxie7683 2017-05-11 21:11
浏览 151
已采纳

一分钟内随机睡觉

Currently I have the following :

$counter = 0;
$actions_per_minute = 6;
$sleep_time = (int)(60 / $actions_per_minute);
do{

    sleep($sleep_time);
    $counter++;

} while($counter < $actions_per_minute);

With this code the script would sleep every 10 seconds is it possible to have it set at random intervals over the 60 seconds just not every 10 seconds so maybe twice in the first 10 seconds, sleep for 7 seconds etc....

  • 写回答

3条回答 默认 最新

  • dongliqian6245 2017-05-11 21:54
    关注

    To generate a list of N random numbers ($actions_per) that add up to a certain value ($total_time):

    $sleep_times = [];
    $actions_per = 6;
    $total_time = 60;
    
    $sum = 0;
    for ($action = 0; $action < $actions_per; $action++ ) {
        $random_interval = rand(0,$total_time);
        array_push($sleep_times, $random_interval);
        $sum = $sum + $random_interval;
    }
    
    $scaleFactor = $sum / $total_time;
    
    $checksum = 0;
    foreach( $sleep_times as $sleep_time ){
        $scaled = $sleep_time / $scaleFactor;
        $checksum = $checksum + $scaled;
        echo $scaled."
    ";
    }
    echo "Check:".$checksum;
    

    Result:

    $actions_per = 6, $total_time = 60:

    9.2523364485981
    3.9252336448598
    12.056074766355
    16.822429906542
    11.495327102804
    6.4485981308411
    Check:60
    

    $actions_per = 12, $total_time = 60:

    9.0532544378698
    8.5207100591716
    6.5680473372781
    2.3076923076923
    9.0532544378698
    3.3727810650888
    3.5502958579882
    4.6153846153846
    4.4378698224852
    2.1301775147929
    4.792899408284
    1.5976331360947
    Check:60
    

    $actions_per = 6, $total_time = 120:

    23.907156673114
    18.568665377176
    3.0174081237911
    25.299806576402
    23.675048355899
    25.531914893617
    Check:120
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了
  • ¥50 切换TabTip键盘的输入法
  • ¥15 可否在不同线程中调用封装数据库操作的类
  • ¥15 微带串馈天线阵列每个阵元宽度计算
  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据