在瑞典最受欢迎的网站之一工作时,我遇到了一个(对我而言)奇怪的片段,它在每个页面上运行:
if( rand(0, 100) === 50 )
// increase visitor count
这样做会生成一个随机数,如果它等于固定数(在这种情况下为50),它将增加访问者数.在显示统计信息的页面上,访问者计数在显示之前乘以例如100.
我确实意识到为每个页面视图写入数据库可能并不理想,特别是对于像这样的非常大的网站.但这真的能产生正确的统计数据吗?仅仅因为99个访客的随机数等于一切,但100并不意味着下一个将获得100.
我反应过度了,还是这是一个糟糕的统计实施?
解决方法:
好的,我想我已经知道了.简而言之 – 这种方法足够准确&我从“瑞典最受欢迎的网站之一”中理解的一种好方法.让我解释:
有三个因素:
>实际访问次数 – 实际的网页浏览量
>跟踪访问 – 跟踪访问,已通过随机数检查的访问
>计算访问次数 – 统计信息页面中显示的访问次数
我可以将其翻译成代码:
如任何页面所示:
//are you here? you are an ACTUAL visit
if(rand(0, 100) === 50){
//are you here? you are a TRACKED visit
//passing info to the database as current number+1
}
并在统计页面中:
//variable $tracked is number of tracked visits from the page
//this is a CALCULATED visit
echo 'Page visits: '.$tracked*100;
我还可以说,实际访问也有可能成为1%的跟踪访问.但现在出现以下问题:为什么我到底需要跟踪1%的访问量?我不能跟踪所有访问吗?
If every page gets 1000 views/min this method is a great
performance booster, and can give rather good results (close enough
to the actual visits).
If every page gets 100 views/min this method can also boost some
performance, and will probably give pretty accurate results.
谈到性能,想象每分钟1000个数据库查询.我个人认为这样做并不好.因此,为了减少查询量,您(或者他们)实际上通过在数据库的入口处放置一个“警卫”来限制对数据库的调用次数,向您询问一个随机问题,只是为了平衡人数内.
当然,你必须找到性能和准确性之间的完美平衡.你可以自己模拟它:
> $actual将帮助您找到最终结果的准确性
> $hits将显示点击次数(人们通过后卫)
> $hit_chance将限制传递结果的数量.性能越高,性能越好,但精度越低.看它!如果设置为100,则机会为%1(1/100),如果设置为10000,则机会为1/10000,如果设置为10 1/10(10%),等等…
> $final将显示计算的访问次数.
$actual = 7000; //set the number of visits you want to check (check the current site statistics!)
$hits = 0; //initialization of variable
$hit_chance = 100; //set hit chance, currently 1%
$answer = intval(round($hit_chance / 2, PHP_ROUND_HALF_UP)); //just set answer between 0 and $hit_chance, which is an integer
for($i=0;$i
if(rand(0, $hit_chance) === $answer){
$hits++;
}
}
$final = $hits * $hit_chance;
$accuracy = 100 - ((($actual - $final) / $actual) * 100);
echo 'Actual visits: '.$actual;
echo '
Hits: '.$hits;
echo '
Final results: '.$final;
echo '
Result accuracy: '.$accuracy.'%';
再想一想,这取决于你 – 我认为没有好/坏的方法.也许服务器非常好,你不需要它,也许它们需要一些性能节省.
标签:php,random,statistics
来源: https://codeday.me/bug/20190709/1412767.html