0

I trying to measure time using Windows command line.

echo %TIME% & timeout 5 > NUL & echo %TIME%

But this command prints two equal timestamps. Why? What I'am doing wrong? timeout 5 is just for example.

double-beep
  • 3,889
  • 12
  • 24
  • 35
Denis Leonov
  • 143
  • 11

2 Answers2

4

The interpreter first parses the whole line (replacing both %time% with the same value (because same time of parsing)) before executing anything. You need delayed expansion to make it work.

If you need a command line solution:

cmd /v /c "echo !time! & timeout 5 & echo !time!"
Stephan
  • 47,723
  • 10
  • 50
  • 81
  • Please, you are a 34.4k reputation, you flag a duplicate and still answer the question? – Matthieu Brucher Dec 18 '18 at 20:35
  • 1
    @MatthieuBrucher I answered the question, and then someone notified me of the duplicate, so I flagged it as such. (it's a quite wordy dupe handling batchfiiles (the command line solution is hidden somewhere in the middle), so it isn't very obvious and I guess most newbies wouldn't catch the point, so I left the answer) – Stephan Dec 18 '18 at 20:45
1

This article https://blogs.msdn.microsoft.com/oldnewthing/20060823-00/?p=29993 says the ENV variables are expanded at the time the command is read. Your results would seem to indicate that the entire command line is read/parsed/expanded at once before anything is executed.

JJF
  • 2,503
  • 2
  • 14
  • 27