Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/243.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PHP中实际运行函数的时间占一定百分比_Php_Random_Anonymous Function - Fatal编程技术网

在PHP中实际运行函数的时间占一定百分比

在PHP中实际运行函数的时间占一定百分比,php,random,anonymous-function,Php,Random,Anonymous Function,如何用PHP编写函数来调用给定函数(匿名)X% 例如: function call_weighted(0.1, function() { echo 'this is actually run approximately 10% of the times it is called'; }); 函数调用\u加权($weight,$function){ 如果(mt_rand()

如何用PHP编写函数来调用给定函数(匿名)
X%

例如:

function call_weighted(0.1, function() {
      echo 'this is actually run approximately 10% of the times it is called';
});
函数调用\u加权($weight,$function){
如果(mt_rand()<$weight*mt_getrandmax()){
$function();
}
}

我认为它工作不正常,使用
1%
它经常调用。在我的测试中,
call_-weighted(0.01,function(){…
,在命中之前,未命中不超过5次。
mt_-rand
返回一个整数,而不是分数。必须将其更改为将最大值乘以权重。
function call_weighted($weight, $function) {
    if (mt_rand() < $weight * mt_getrandmax()) {
        $function();
    }
}