2011-09-28 141 views
1

我試圖在PHP中創建一個簡單的拆分測試器,但我在獲取百分比時都遇到了一些麻煩。在PHP中使用百分比

所以,我有一個設置頁面,我想要放一個百分比,比如20,這樣20%的流量到我的頁面將被重定向。

這顯然需要與rand一起工作,但我不確定如何。

+0

你是說你想設置的時間加載頁面重定向20%? –

+0

目前尚不清楚你想要達到的目標。你試過什麼了?給我們一些代碼! – Alex

+0

這是A-B測試。 – jancha

回答

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 
+0

我會用1和5代替。 – mowwwalker

+0

這給出了更好的表示。你可以試試。實際上,有時候是 – jancha

+0

。 – jancha

4

這個if語句返回20%真:

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