我正在尝试编写一个TCL过程,它将允许我包装语句,然后在内部'执行'它们。
例如,如果我原来有:
set var $tmp
我想做一些程序:
proc wrapper {command} {
puts "do something here"
puts $command #ie below : write "set var $tmp" to stdout
EXECUTE COMMAND HERE
puts "do something else here"
}
set void [wrapper {set var $tmp}]
我的动机是我试图为单个语句编写我自己的计时/分析器。
用
代替"EXECUTE COMMAND"uplevel 1 $command
请注意,如果您尝试使用像wrapper
这样的命令来计时脚本,它将不会被字节编译,这意味着它不会像在过程中那样执行。
文档:uplevel
您可以尝试使用time
命令,如果您唯一的意图只是获得一组代码执行所花费的时间,那么Tcl
命令已经可用。
时间脚本?count?
该命令将调用Tcl
解释器count
次来评估脚本(如果没有指定count
,则调用一次)。然后它将返回一个形式为
503.2 microseconds per iteration
表示每次迭代所需的平均时间,以微秒为单位。时间是以经过的时间来衡量的,而不是CPU时间。
例子:
set code_block {
foreach x "1 2 3" {
set y [expr {$x*20}];
}
}
puts [time $code_block 10]; # Executing the code for 10 times
可能产生随机输出,如
11.9 microseconds per iteration
更新1:
如果您想在执行时打印命令,这也是可能的。可以用rename
命令覆盖time
命令。
rename time _time; # Changing the 'time' to '_time'
# Defining your own 'time' command
proc time {command {count 1}} {
# Printing the commands here
puts $command
# Calling the actual '_time' command
# and returning that value from here
return [_time $command $count]
}
将上面的代码放在代码的顶部,在此之后使用time
命令将只使用我们的自定义过程。
它们作为一组命令传递,然后,是的,是一个字符串。但是,在计算代码时,它的行为就像在tclsh
中工作一样。
正如Mr.Peter所回答的,如果你的代码涉及到访问前一级的命令、变量,那么你必须根据你的需要使用uplevel
或upvar
。
,重命名