我的 PHP 代码包含很多 foreach 循环,结果绝对是灾难性的。运行时间太长了。
有没有替代方案。我愿意接受所有建议。
我在想可能正在实现一个基于 Flash 的客户端并使用 actionscript 来利用客户端的 CPU 来运行逻辑。
或者有没有办法使用 C/C++ 来处理服务器本身的计算要求高的部分并返回 PHP 结果。
以下函数被调用 1,000,000 次。
public function performEnrichmentAnalysis($geneSet) {
/**
* $mainArray is a multi dimentional array.
* EntrezID | Set (0/1) | pValue | rank
*/
$mainArray = array();
$finalArray = array();
$originalGenesScore = 0;
$randomGenesScore = 0;
$u = 0;
$EntrezID = array();
$Set = array();
$pValue = array();
$Rank = array();
$originalGenes = $geneSet->getGenes();
$memeberCount = $geneSet->getGeneCount();
$randomGenes = $this->geneExpressionData->getRandomGenes($memeberCount);
/**
* Copy the elements of original and random gene sets to main array.
*/
foreach ($originalGenes as $key => $value) {
$pVal = $this->geneExpressionData->getExpressionValue($value);
$array = array('EntrezID' => $value, 'Set' => 0, 'pValue' => $pVal, 'Rank' => 999);
array_push($mainArray, $array);
unset($array);
}
foreach ($randomGenes as $key => $value) {
$pVal = $this->geneExpressionData->getExpressionValue($value);
$array = array('EntrezID' => $value, 'Set' => 1, 'pValue' => $pVal, 'Rank' => 999);
array_push($mainArray, $array);
unset($array);
}
/**
* sort the multi dimentaional array based on p-values
*/
foreach ($mainArray as $key => $row) {
$EntrezID[$key] = $row['EntrezID'];
$Set[$key] = $row['Set'];
$pValue[$key] = $row['pValue'];
$Rank[$key] = $row['Rank'];
}
array_multisort($pValue, SORT_ASC, $mainArray);
/**
* Assign ranks to the genes
*/
for ($index = 0; $index < count($mainArray); $index++) {
$row = $mainArray[$index];
$row['Rank'] = $index + 1;
$row['Score'] = 0;
//print_r($row['Rank']);
array_push($finalArray, $row);
}
/**
* Calculate scores for each gene
*/
for ($i = 0; $i < count($finalArray); $i++) {
for ($j = $i + 1; $j < count($finalArray); $j++) {
if ($finalArray[$j]['Set'] != $finalArray[$i]['Set']) {
$finalArray[$i]['Score']++;
}
}
}
/**
* Calculate score for the entire set and get universal U and z score.
*/
for ($counter = 0; $counter < count($finalArray); $counter++) {
if ($finalArray[$counter]['Set'] == 0) {
$originalGenesScore += $finalArray[$counter]['Score'];
}
if ($finalArray[$counter]['Set'] == 1) {
$randomGenesScore += $finalArray[$counter]['Score'];
}
}
if ($originalGenesScore > $randomGenesScore) {
$u = $randomGenesScore;
} else {
$u = $originalGenesScore;
}
$zNumerator = $u - (($memeberCount * $memeberCount) / (2));
$zDenominatorSquared = ($memeberCount * $memeberCount * ($memeberCount + $memeberCount + 1)) / 12;
$z = $zNumerator / sqrt($zDenominatorSquared);
if (abs($z) > 2.303) {
$this->temp001++;
} elseif (abs($z) > 1.605) {
$this->temp005++;
} else {
$this->tempRemaining++;
}
}