[英]How to make my phrase counter run faster
我有一個短語計數器功能作為我想適應於運行非常大的數據集的類的一部分
<?php
private static function do_phrase_count($words, $multidim, $count, $pcount){
if($multidim === false){
$words = array($words);
}
$tally = array();
$arraycount = 0;
foreach($words as $wordgroup){
$max = count($wordgrounp) - $pcount;
for($x = 0; $x < $max; $x++){
$cutoff = $x + $pcount;
$spacekey = false;
$phrase = '';
$z = 0;
for($y = $x; $y < $cutoff; $y++){
if($spacekey) $phrase .= ' ';
else $spacekey = true;
$phrase .= $wordgroup[$y + $z];
$z++;
}
if(isset($tally[$phrase])){
$tally[$phrase]++;
$arraycount++;
}
else $tally[$phrase] = 1;
if($arraycount > 99999){
arsort($tally);
$tally = array_slice($tally, 0, 50000);
$arraycount = 49999;
}
}
}
arsort($tally);
$out = array_slice($tally, 0, $count);
return $out;
}
每次迭代時,array_key_exists變慢,因此在某個時候,我需要減小計數集的大小。
我當時正在考慮使用限制(100K)來阻止腳本將新的數組元素添加到$ tally,甚至不使用總單詞數的百分比,但是當我停止向數組中添加新元素后,我就無法跟蹤可能出現的趨勢彈出。 (如果我要分析一整年的數據,那么到6月時,我將無法看到“夏令時”為趨勢)。
任何人都有解決方案,如何限制我的理貨記錄數組,以保持腳本的准確性而不丟失跟蹤趨勢的能力?
更新:我根據您的建議更改了腳本。 感謝您的幫助。 我還想出了一種減小陣列大小的解決方案。
除了Cheery的答案外,還從for循環中刪除count($var)
。 每次迭代時,您都不必要地重新計算$ var的大小。
$groupsize = count($wordgroup) - $pcount;
for($x = 0; $x < $groupsize; $x++){
//...
if(isset($tally[$phrase]))
$tally[$phrase]++;
else
$tally[$phrase] = 1;
它應該比array_key_exists
更快
ps:測試樣本
function genRandomString($length) {
$characters = '0123456789abcdefghijklmnopqrstuvwxyz';
$string = '';
for ($p = 0; $p < $length; $p++) {
$string .= $characters[mt_rand(0, strlen($characters)-1)];
}
return $string;
}
function microtime_float()
{
list($usec, $sec) = explode(" ", microtime());
return ((float)$usec + (float)$sec);
}
$len = 1000000; $str = genRandomString($len);
$tally = array();
$stamp1 = microtime_float();
for($i=0; $i<$len; $i++)
{
if(array_key_exists($str[$i], $tally))
$tally[$str[$i]]++;
else
$tally[$str[$i]] = 1;
}
echo microtime_float() - $stamp1 . '<br />';
$tally = array(); $stamp1 = microtime_float();
for($i = 0; $i<$len; $i++)
{
if(isset($tally[$str[$i]]))
$tally[$str[$i]]++;
else
$tally[$str[$i]] = 1;
}
echo microtime_float() - $stamp1 . '<br />';
結果:
0.80751395225525
0.44111108779907
當然,這里的密鑰數量是有限的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.