Können Sie mir bitte sagen, warum zweiter Code zweimal schneller läuft als der erste Code (6 Sek. Und 11 Sek.) (In allen PHP-Versionen)? Der Grund ist für die Verwendung von Funktionen oder die Verwendung von globalen oder irgendetwas anderes und warum? Ich möchte diesen Fehler in anderem Skript verhindern, aber ich weiß nicht, was genau mein Fehler ist.Welcher Teil braucht mehr Zeit, Funktion oder global?
Ich führe dieses Skript mit Online-Tools, aber haben das gleiche Ergebnis.
Profil erster Code: erster Code:
for ($i = 1; $i < 2500; ++$i) {
$pen[$i] = $i * (3 * $i - 1)/2;
}
function pentagonal($num) {
global $pen;
return $pen[$num];
}
function is_pentagonal($c) {
$x = (1+sqrt(1+24*$c))/(6);
if ($x == (int)$x) {
return true;
} else {
return false;
}
}
for ($i = 2; ; ++$i) {
for ($j = 1; $j < $i ; ++$j) {
$pi = pentagonal($i); // Here is the difference
$pj = pentagonal($j); // Here is the difference
if (is_pentagonal($pi + $pj, $pen)) {
if (is_pentagonal(abs($pi - $pj), $pen)) {
$difference = $pi - $pj;
break 2;
}
}
}
}
echo $i.' '.$j.' '.$difference."\n";
zweiter Code (nur Funktion zu entfernen und den Wert direkt aus dem Array erhalten):
for ($i = 1; $i < 2500; ++$i) {
$pen[$i] = $i * (3 * $i - 1)/2;
}
// function pentagonal($num) {
// global $pen;
// return $pen[$num];
// }
function is_pentagonal($c) {
$x = (1+sqrt(1+24*$c))/(6);
if ($x == (int)$x) {
return true;
} else {
return false;
}
}
for ($i = 2; ; ++$i) {
for ($j = 1; $j < $i ; ++$j) {
$pi = $pen[$i]; // Here is the difference
$pj = $pen[$j]; // Here is the difference
if (is_pentagonal($pi + $pj, $pen)) {
if (is_pentagonal(abs($pi - $pj), $pen)) {
$difference = $pi - $pj;
break 2;
}
}
}
}
echo $i.' '.$j.' '.$difference."\n";