Re: Efficient looping
From: sheila miguez (she_at_removethis.pobox.com.invalid)
Date: 11/14/04
- Previous message: Binny V A: "Tutorial Version 2"
- In reply to: Bryan Oakley: "Re: Efficient looping"
- Next in thread: lvirden_at_gmail.com: "Re: Efficient looping"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Sun, 14 Nov 2004 13:50:24 -0600
In article <tMUkd.29800$Al3.6344@newssvr30.news.prodigy.com>, Bryan
Oakley <oakley@bardo.clearlight.com> wrote:
> Use the time command to figure out the answer. Put an executable
> statement in the loop then run each loop and see which one goes faster:
>
> set t1 [time {foreach i [range 1 1000000] {
> set x $i
> }}]
>
> set t2 [time {for {set i 0} {$i < 1000000} {incr i} {
> set x $i
> }}]
I usually make a small proc for each approach and have an argument to
allow me to vary the size of input. This is not needed for the poster's
question, but it may be illustrative to other people:
proc testforeach {n} {
foreach i [range 1 $n] {
set x $i
}
}
proc testfor {n} {
for {set i 0} {$i < $n} {incr i} {
set x $i
}
}
and test with different values of 'n'. I don't have [range] so I only
have an example for the second.
% time {testfor 10} 1000
22 microseconds per iteration
% time {testfor 10000} 1000
15889 microseconds per iteration
% time {testfor 10000}
14797 microseconds per iteration
etc.
Passing a large number of iterations to time increases accuracy?
I've tweaked code that was operating on lists via a for loop and a
string index command. I was curious as to whether a foreach over a
[split $str {}] would be any faster. Not much difference for very short
strings, but I saw an improvement for longer strings, iirc.
Since the function was being used for both long and short strings, and
since the new way to do it was much more readable, I went ahead and
changed it to the foreach way.
aside:
C Programmers new to tcl think in for loops instead of foreach loops.
-- sheila
- Previous message: Binny V A: "Tutorial Version 2"
- In reply to: Bryan Oakley: "Re: Efficient looping"
- Next in thread: lvirden_at_gmail.com: "Re: Efficient looping"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|