TABLE OF CONTENTS


::pwtk::time2ms

SYNOPSIS

proc ::pwtk::time2ms {opt {time {}}} {

USAGE

   time2ms  ?-real?  TIME

PURPOSE

Convert the time to milliseconds and round it to an integer, unless the -real option is specified.

OPTION

ARGUMENT

Units of time ("*" implies any string, e.g., micro* matches microseconds):

SOURCE

    if { [string match -r* $opt] } {
        # time2ms -real time
        set real 1
    } elseif { $time eq {} } {
        # time2ms time
        set real 0
        set time $opt
    } else {        
        ::pwtk::error "wrong args: should be \"time2ms  ?-real?  TIME\", but got \"[procName] $opt [list $time]\"" 1
    }

    set unit  [string trim [regsub {^[\-+0-9.eE]+} $time {}]]
    set value [regsub [string trim $unit] $time {}]
    if { ! [string is double $value] } {
        ::pwtk::error "wrong time \"$time\", time should be a number" 1
    }
    ifempty value { set value 1 }

    # in seconds:
    set min   60
    set hour  3600
    set day   [expr {24*$hour}]
    set week  [expr {7*$day}]
    set month [expr {30*$day}]
    set year  [expr {365*$day}]        

    switch -glob $unit {
        micro*        { set sec 1e-6 }
        ms            { set sec 1e-3 }
        s - sec*      { set sec 1 }
        m - min*      { set sec $min }
        h - H - hour* { set sec $hour }
        d - D - day*  { set sec $day }
        w - W - week* { set sec $week }
        M - mon*      { set sec $month }
        y - Y - year* { set sec $year }
        {} {
            # no unit: default time-unit is second
            set sec 1
        }
        default {
            pwtk::error "wrong unit \"$unit\", must be one of microsec, ms, s, m, h, d, w, N, y" 1
        }
    }

    # return time in ms
    set time [expr {1000 * $sec * $value}]
    if { $real } {
        return [expr double($time)]
    } else {
        return [expr {round($time)}]
    }
}