My own control structures are slow
- From: Christian Gollwitzer <auriocus@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>
- Date: Thu, 29 Sep 2005 19:23:14 +0200
Hi all,
in Tcl one can add one's own control structures to the language, but I see that it is very hard to get it right. I want to add some for loops to an interactive program that uses tcl with tkcon as a command line interpreter. An often used pattern is to iterate over an image with 512x512 pixels, and because it is tedious to type in all those for loops I decided to add a function MAP. My first try was:
proc MAP command {
upvar x x y y
for {set x 0} {$x<=511} {incr x} {
for {set y 0} {$y<=511} {incr y} {
uplevel $command
}
}
}then you can do something like
MAP { set sum [expr {$sum+$x+$y}]}this works, but is very slow (2.3 seconds). Actually it seems to be very hard to do this right.
My second try was to move the for loops into the upper level:
proc MAP2 command {
uplevel 1 [list for {set x 0} {$x<=511} {incr x} [
list for {set y 0} {$y<=511} {incr y} $command
]]
}This is way faster, it takes only 0.4 seconds
My third try was to put the body into a procedure to force bytecode compilation:
proc MAP3 command {
uplevel 1 [list proc mapbody {} [list for {set y 0} {$y<512} {incr y} [list for {set x 0} {$x<512} {incr x} $command]]]
uplevel 1 mapbody
}
This kind of works, but now the upper level variables are not accessible, so
MAP3 { set sum [expr {$sum+$x+$y}]}
failes with 'can't read "sum": no such variable'
but if I use this procedure eg. with
MAP3 { set sum [expr {$x+$y}]}it is much, much faster than the other variants (73 milliseconds!) due to bytecode compilation. Trying to fix the problem with the variable context by inserting "uplevel" like:
MAP3 { uplevel 1 {set sum [expr {$sum+$x+$y}]}}makes it as slow as the first version (2.3 s)
the fault seems to be that uplevel hinders bytecode compilation. How to do these control structure thingy right?
Christian .
- Follow-Ups:
- Re: My own control structures are slow
- From: Donald Arseneau
- Re: My own control structures are slow
- From: Donald Arseneau
- Re: My own control structures are slow
- From: Christian Gollwitzer
- Re: My own control structures are slow
- Prev by Date: Re: Tcl vs. Python
- Next by Date: Re: My own control structures are slow
- Previous by thread: retrieving line number in case of error - "simple debugger"
- Next by thread: Re: My own control structures are slow
- Index(es):
Relevant Pages
|