在Tcl中用time来测试命令的执行速度

风行水上 @ 2010-04-22 17:08:53
标签:

    速度,是人们不变的追求之一。程序也是这样。因此有必要研究实现同样功能的不同代码怎样可以运行的更快。

    Tcl 内置了一个 "time" 命令用来计算一段 Tcl 代码的平均运行速度。用法如下:

    set a 3.5
    set b 1.3
    time { puts [expr $a+$b] } 100
    # 返回字符串: 9 microseconds per iteration
    

    利用 time 命令,我们可以得出以下一些结论

    怎样让 expr 命令更快

    如果Tcl程序要做大量数值运算的话,这绝对是值得优化的一个地方。

    time { set r [expr {$a+$b}] } 1000000  ; # 0 microseconds per iteration
    time { set r [expr $a + $b]} 1000000   ; # 3 microseconds per iteration  
    time { set r [expr $a+$b]} 1000000     ; # 3 microseconds per iteration
    

    可以看出,通过把表达式用大括号括起来,可以使运行速度提高一倍。原因大概是计算式的解析由内部代码完成,省去了Tcl命令行的处理过程(比如参数替换操作)。

    标签:

      分享到:
      comments powered by Disqus

      27/31ms