我的PHP代码包含许多foreach循环,并且结果绝对是灾难性的。运行时间太长。优化使用大量for循环的PHP代码
是否有替代方案。我接受所有建议。
我在想,可能会实现基于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++;
}
}
我们需要看到代码,如果你想我们tobhelp你优化。 Alo代码优化可能更多关于[代码评论](http://codereview.stackexchange.com)主题 – 2013-03-02 21:18:26
我觉得你的问题有点太模糊。你没有告诉我们关于你在这些循环中遍历的数据以及你正在运行的计算的任何信息。 – 2013-03-02 21:19:27
对,谢谢。我现在发布了代码。 – Pranjal 2013-03-02 21:24:01