Two things leap out about the original batch file. but neither is going to help in the long run.
Whatever your benchmark method, be sure to capture the start time before the operation, and the end time after the operation. Your sample doesn't do that.
%time%
evaluates to something like "12:34:56.78", and the SET /A
command can't subtract those. You need a command that produces a simple scalar time stamp.
I was going to say it can't be done, but the batch language is a lot more powerful than it is given credit for, so here is a simple implementation of TIMER.BAT. For the record, Pax beat me to an answer showing the string splitting while I was fiddling around, and Johannes Rössel suggested moving the arithmetic outside of the measured region:
@echo off
setlocal
set t0=%time%
rem do something here.... but probably with more care about quoting ;-)
%1 %2 %3 %4 %5 %6 %7 %8 %9
set t=%time%
rem make t0 into a scaler in 100ths of a second
set h=%t0:~0,2%
set m=%t0:~3,2%
set s=%t0:~6,2%
set c=%t0:~8,2%
set /a starttime = %h% * 360000 + %m% * 6000 + 100 * %s% + %c%
rem make t into a scaler in 100ths of a second
set h=%t:~0,2%
set m=%t:~3,2%
set s=%t:~6,2%
set c=%t:~8,2%
set /a endtime = %h% * 360000 + %m% * 6000 + 100 * %s% + %c%
rem runtime in 100ths is now just end - start
set /a runtime = %endtime% - %starttime%
set runtime = %s%.%c%
echo Script took %runtime%0 ms to complete
You could simplify the arithmetic and be a little more honest about the overall accuracy of this by not bothering with the 100ths of a second part. Here it is in action, assuming you have a sleep command or some other time waster:
C:> TIMER SLEEP 3
Script took 3000 ms to complete
C:>
Edit: I revised the code and its description as suggested in a comment.
I think that when the NT team replaced COMMAND.COM with CMD.EXE, they thought they wouldn't get away with making it very different. But in effect, it is almost an entirely new language. Many of the old favorite commands have new features if the extensions are enabled.
One of those is SETLOCAL
which prevents variables from modifying the caller's environment. Another is SET /A
which gives you a remarkable amount of arithmetic. The principle trick I've used here is the new substring extraction syntax where %t:~3,2% means the two characters starting at offset 3 in the value of the variable named
t`.
For a real shocker, take a look at the full description of set (try SET /?
at a prompt) and if that doesn't scare you, look at FOR /?
and notice that it can parse text out of files...