#!/usr/bin/perl -w use strict; use Benchmark; timethese([X], { 'while' => sub { $_ = 0; while (1) { $_++; last if ($_ == 1000); + } }, 'for' => sub { $_ = 0; for (;;) { $_++; last if ($_ == 1000); + } }, 'block' => sub { $_ = 0; { $_++; redo if ($_ < 1000); + } } });
And after running this code with several different iterations (being the scientific person that I am), I came up with the following results:
Benchmark: timing 10000 iterations of block, for, while... block: 8 wallclock secs ( 8.13 usr + 0.00 sys = 8.13 CPU) for: 8 wallclock secs ( 7.90 usr + 0.00 sys = 7.90 CPU) while: 8 wallclock secs ( 8.03 usr + 0.00 sys = 8.03 CPU) Benchmark: timing 20000 iterations of block, for, while... block: 16 wallclock secs (16.25 usr + 0.00 sys = 16.25 CPU) for: 16 wallclock secs (15.80 usr + 0.00 sys = 15.80 CPU) while: 16 wallclock secs (16.08 usr + 0.00 sys = 16.08 CPU) Benchmark: timing 30000 iterations of block, for, while... block: 24 wallclock secs (24.37 usr + 0.00 sys = 24.37 CPU) for: 24 wallclock secs (23.69 usr + 0.00 sys = 23.69 CPU) while: 24 wallclock secs (24.08 usr + 0.00 sys = 24.08 CPU) Benchmark: timing 80000 iterations of block, for, while... block: 66 wallclock secs (65.01 usr + 0.00 sys = 65.01 CPU) for: 63 wallclock secs (63.18 usr + 0.00 sys = 63.18 CPU) while: 64 wallclock secs (64.20 usr + 0.00 sys = 64.20 CPU)
And once again, Programming Perl was absolutely right. The "for" loop was not only the customary infinite loop to use, but also the most efficient infinite loop to use. So now, I have been converted from while (1) { ... } to for (;;) { ... } and hopefully others will soon be converted, too.
Zenon Zabinski | zdog | zdog7@hotmail.com
Update: indigo pointed me in the direction of while() down the thread, and as you can see below, I found that while() was indeed faster than for(;;). Soo....
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
(tye)RE: The Best Infinite Loop
by tye (Sage) on Oct 17, 2000 at 10:23 UTC | |
by rdw (Curate) on Oct 17, 2000 at 14:23 UTC | |
by BlaisePascal (Monk) on Oct 18, 2000 at 02:16 UTC | |
|
RE (tilly) 1: The Best Infinite Loop
by tilly (Archbishop) on Oct 17, 2000 at 04:31 UTC | |
|
RE: The Best Infinite Loop
by Adam (Vicar) on Oct 17, 2000 at 02:32 UTC | |
|
RE: The Best Infinite Loop
by indigo (Scribe) on Oct 17, 2000 at 06:01 UTC | |
by zdog (Priest) on Oct 18, 2000 at 01:51 UTC | |
|
RE: The Best Infinite Loop
by wardk (Deacon) on Oct 17, 2000 at 21:14 UTC | |
|
Re: The Best Infinite Loop
by jdhedden (Deacon) on Jun 08, 2005 at 12:32 UTC | |
|
RE: The Best Infinite Loop
by AgentM (Curate) on Oct 17, 2000 at 02:23 UTC |