Code snippet #2: timed command
Rationale: one good thing about REXX is that it lets you use system commands in your code, which makes integrating both very easy. It is sometimes interesting to know how long some commands take to complete, so why not use some simple REXX to execute them and find out?
This REXX code will take its execution parameters as a command to be executed as is by the system shell, will report the time elapsed, and pass along its exit (return) code:
/*
Timed Command: executes its invoking parameters as an
external system command, and tells how long it took
*/
parse arg command
/* Depending on command output, this may go off-screen > repeat at the end */
start = time()
say 'Starting "'||command||'" at '||start
call time 'E' /* start timer */
/* Single literals execute as commands */
'@Echo Off'
command
cmdrc = rc /* save return code */
say 'Command: "'||command||'", '||,
'started at '||start||', ended at '||time()||'. '||,
'Elapsed: '||format(time('E'),,2)||'s.'
if cmdrc <> 0 then /* simple warning */
say 'Non-zero exit code (error?): '||cmdrc
exit cmdrc /* RC is passed along regardless of value */
Some refinements are possible. For example, time can be formatted if too many seconds are uncomfortable to read:
[...]
say 'Command: "'||command||'", '||,
'started at '||start||', ended at '||time()||'. '||,
'Elapsed: '||t2hms(time('E'))||'.'
if cmdrc <> 0 then /* simple warning */
say 'Non-zero exit code (error?): '||cmdrc
exit cmdrc /* RC is passed along regardless of value */
t2hms: procedure
parse arg t
h = t % 3600
t = (t // 3600)
m = t % 60
s = (t // 60)
t = format(s,,2)||'s'
if (m > 0) then do
if (s < 10) then
t = '0'||t
t = m||'m:'||t
end
if (h > 0) then do
if (m < 10) then
t = '0'||t
t = h||'h:'||t
end
return t
What if commands include redirection?
Some commands are most useful when executed redirecting their output to a file, e.g. "dir > filelist.txt", but executing "TimedCmd dir > filelist.txt" will include TimedCmd output in filelist.txt in the example, which may not be desirable.
To adress such situations, the whole command must be in quotes so it is passed as a single parameter for execution leaving the redirection to be processed later, i.e. TimedCmd "dir > filelist.txt" in the example above. However, the quotes must be removed from both ends so the system shell will break the command again to carry on the redirection, instead of looking for a file called "dir > filelist.txt" to execute:
[...]
parse arg command
command = strip(command,,'"')
[...]
Edit: tt -> code