在PHP中实际运行函数的时间占一定百分比
如何用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()
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();
}
}