如何按百分比运行代码

问题描述 投票:0回答:3

在我的脚本中,我想在一定比例的时间内运行某些代码,我查看了 StackOverflow 并找到了下面的代码。 它运行代码的时间为 33%,我需要修改什么才能让它运行 55% 和 70% 的时间?

$max = 27;

for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
        call_function_here();
    }
}
php
3个回答
10
投票

最简单的方法是使用随机数生成器并测试其结果是否小于(或大于,无关紧要)您的目标数量。

function percentChance($chance){
  // Notice we go from 0-99 - therefore a 100% $chance is always larger
  $randPercent = mt_rand(0,99);
  return $chance > $randPercent;
}

...

if(percentChance(30)){
  // 30% of page loads will enter this block
}

if(percentChance(100)){
  // All page loads will enter this block
}

if(percentChance(0)){
  // No chance this block will ever be entered
}

0
投票

握住它。这些代码都不起作用。是我复制粘贴错误还是版本不对?如果是,请有人发布一些有帮助的内容。我需要最新版本的 python (3.12.3)


-1
投票

由于选择的金额必须恒定,您可以这样做:

$max = 27;
$num_selections = round(27 * (55 / 100));
$keys = array_rand($max, $num_selections);
for ($keys as $key) {
    // Do something with the chosen key
}
© www.soinside.com 2019 - 2024. All rights reserved.