使用PHP中的百分比

时间:2011-09-28 20:29:58

标签: php

我正在尝试在PHP中创建一个简单的拆分测试程序,但是我在查找百分比时遇到了一些麻烦。

所以,我有一个设置页面,我想放一个百分比,比如20,这样我页面的20%流量都会被重定向。

这显然需要与rand一起工作,但我不确定如何。

2 个答案:

答案 0 :(得分:4)

此if语句返回20%true:

if (rand(1,5) % 5 == 0)

答案 1 :(得分:2)

if (rand(1, 100) <= 20){
   // show page 1
} else {
   // show page 2
}

一些测试和比较:

Results for round 0
Method1 redirect rate: 0.200302%
Method2 redirect rate: 0.200318%
Results for round 1
Method1 redirect rate: 0.199277%
Method2 redirect rate: 0.199479%
Results for round 2
Method1 redirect rate: 0.200262%
Method2 redirect rate: 0.19995%
Results for round 3
Method1 redirect rate: 0.200254%
Method2 redirect rate: 0.200315%
Results for round 4
Method1 redirect rate: 0.199943%
Method2 redirect rate: 0.19977%
Results for round 5
Method1 redirect rate: 0.20006%
Method2 redirect rate: 0.20024%
Summary:
Method1 deviation: -9.7999999999931E-5
Method2 deviation: -7.1999999999905E-5

和该测试的代码:

<?php
function method1(){
    return (rand(1,5) % 5 == 0)?true:false;
}
function method2(){
    return (rand(1,100) <= 20)?true:false;
}

$iterations = 1000000;

for ($j = 0; $j <= 5; $j++){
    $m1 = 0;
    $m2 = 0;
    for ($i = 0; $i < $iterations; $i++){
        if (method1()){
            $m1++;
        }
        if (method2()){
            $m2++;
        }
    }
    $dx1 = $m1/$iterations;
    $dx2 = $m2/$iterations;
    $dev1 += 0.2 - $dx1;
    $dev2 += 0.2 - $dx2;
    echo "Results for round $j\n";
    echo "Method1 redirect rate: " . $dx1 . "%\n";
    echo "Method2 redirect rate: " . $dx2 . "%\n";
}
echo "Summary:\n";
echo "Method1 deviation: $dev1\n";
echo "Method2 deviation: $dev2\n";

同样<将比%占用更少的CPU功率:)首先,时间是%然后是<

$ /usr/bin/time -l php -q test.php 
        5.25 real         5.19 user         0.01 sys
   8224768  maximum resident set size
         0  average shared memory size
         0  average unshared data size
         0  average unshared stack size
      2090  page reclaims
         0  page faults
         0  swaps
        17  block input operations
         4  block output operations
         0  messages sent
         0  messages received
         0  signals received
        17  voluntary context switches
       592  involuntary context switches



$ /usr/bin/time -l php -q test.php 
        4.75 real         4.73 user         0.01 sys
   8216576  maximum resident set size
         0  average shared memory size
         0  average unshared data size
         0  average unshared stack size
      2088  page reclaims
         0  page faults
         0  swaps
         0  block input operations
         0  block output operations
         0  messages sent
         0  messages received
         0  signals received
         0  voluntary context switches
       100  involuntary context switches