note 34178 modified in control-structures.for by vrana
| From: | vrana@php.net | Date: | Thu, 05 Aug 2004 18:11:34 +0000 |
| Subject: | note 34178 modified in control-structures.for by vrana | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-74060@lists.php.net to get a copy of this message | ||
If you're already using the fastest algorithms you can find (on the order of O(1), O(n), or O(n
log n)), and you're still worried about loop speed, unroll your loops using e.g., Duff's
Device:
<?php
$n = $ITERATIONS % 8;
while ($n--) $val++;
$n = (int)($ITERATIONS / 8);
while ($n--) {
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
}
?>
(This is a modified form of Duff's original device, because PHP doesn't understand the
original's egregious syntax.)
That's algorithmically equivalent to the common form:
<?php
for ($i = 0; $i < $ITERATIONS; $i++) {
$val++;
}
?>
$val++ can be whatever operation you need to perform ITERATIONS number of times.
On my box, with no users, average run time across 100 samples with ITERATIONS = 10000000 (10
million) is:
Duff version: 7.9857 s
Obvious version: 27.608 s
--was--
If you're already using the fastest algorithms you can find (on the order of O(1), O(n), or O(n
log n)), and you're still worried about loop speed, unroll your loops using e.g., Duff's
Device:
$n = $ITERATIONS % 8;
while ($n--) $val++;
$n = (int)($ITERATIONS / 8);
while ($n--) {
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
$val++;
}
(This is a modified form of Duff's original device, because PHP doesn't understand the
original's egregious syntax.)
That's algorithmically equivalent to the common form:
for ($i = 0; $i < $ITERATIONS; $i++) {
$val++;
}
$val++ can be whatever operation you need to perform ITERATIONS number of times.
On my box, with no users, average run time across 100 samples with ITERATIONS = 10000000 (10
million) is:
Duff version: 7.9857 s
Obvious version: 27.608 s
http://php.net/manual/en/control-structures.for.php