scriptingtclperformance-testingcpu-time

How to measure cpu time of TCL script


I have long TCL script . I want measure exact cpu time the process is taking in TCL

I tried the time command in TCL but I am not sure it is correct way to measure cpu time taken by complete TCL script


Solution

  • Tcl itself doesn't provide this information. You want to use the TclX package's times command.

    package require Tclx
    
    set pre [times]
    # do CPU intensive operation here; for example calculating the length of a number with many digits...
    string length [expr {13**12345}]
    set post [times]
    
    # the current process's non-OS CPU time is the first element; it's in milliseconds
    set cpuSecondsTaken [expr {([lindex $post 0] - [lindex $pre 0]) / 1000.0}]
    # The other elements are: system-cpu-time, subprocess-user-cpu-time, subprocess-system-time
    

    You are, of course, dependent on the OS measuring this information correctly. It's not portable to non-POSIX systems (e.g., Windows) though there might be something logically similar in the TWAPI package.