- Sleep/Timeout command in Windows 7
- Timeout command
- Sleep command
- Timer. Elapsed Событие
- Определение
- Тип события
- Примеры
- Комментарии
- knadh / zsh-elapsed-time.md
- This comment has been minimized.
- kimonoki commented May 18, 2019 •
- This comment has been minimized.
- jep-dev commented Jul 13, 2019 •
- This comment has been minimized.
- knadh commented Jul 14, 2019
- This comment has been minimized.
- knadh commented Jul 14, 2019
- This comment has been minimized.
- rufreakde commented Aug 13, 2019 •
- Print time in a batch file (milliseconds)
- 7 Answers 7
- Calculate time difference in Windows batch file
- 10 Answers 10
Sleep/Timeout command in Windows 7
There are two commands which we can use to make a batch command sleep for some time. The native available ‘timeout’ command and the resource kit tool ‘sleep’.
Timeout command
We can use ‘timeout’ command in Windows 7 to pause execution for some time and then continue. We can specify the number of seconds to wait, it would wait till the time elapses or until user presses any key.
Example: To wait for 10 seconds
Example: To sleep for 2 minutes and ignore any key presses
Sleep command
Windows provides a resource kit tool ‘sleep’ which can be used in batch files or command prompt to pause the execution and wait for some time. Though the tool was intended for XP, I have used it on Windows 7 and it works perfectly fine. Find the download location and installation instructions here :Download Windows resource kit tools .
Syntax of sleep command:
Examples:
If you want to pause the execution of a batch file for 50 seconds, then you should insert below statement in your batch file.
If you want to wait for 100 milli seconds, then you can run the below command.
Sleep command should also work find on Server 2008 and Server 2008 R2.
Instead of downloading extra tools, you can stick with the ping command as well:
ping /t 50 localhost
will “sleep” 50 secs before going on
Out of curiosity, I compared ping vs timeout and both seem to have stopped exactly at the same time. However, with the availability of timeout command, we don’t have to look for such alternatives.
Excuse my typo. For 50 sec sleep, use
ping localhost -n 50
in Windows Vista an later, you can use Timeout /t
Timer. Elapsed Событие
Определение
Происходит по истечении интервала времени. Occurs when the interval elapses.
Тип события
Примеры
В следующем примере создается экземпляр Timer объекта, который запускает Timer.Elapsed событие каждые две секунды (2000 миллисекунд), настраивает обработчик событий для события и запускает таймер. The following example instantiates a Timer object that fires its Timer.Elapsed event every two seconds (2000 milliseconds), sets up an event handler for the event, and starts the timer. Обработчик событий отображает значение ElapsedEventArgs.SignalTime свойства при каждом его возникновении. The event handler displays the value of the ElapsedEventArgs.SignalTime property each time it is raised.
Комментарии
ElapsedСобытие возникает, если Enabled свойство имеет значение true и интервал времени (в миллисекундах), определенный Interval свойством, истекает. The Elapsed event is raised if the Enabled property is true and the time interval (in milliseconds) defined by the Interval property elapses. Если AutoReset свойство имеет значение true , событие вызывается несколько раз с интервалом, определенным Interval свойством; в противном случае событие вызывается только один раз, когда Interval истечет первое время. If the AutoReset property is true , the event is raised repeatedly at an interval defined by the Interval property; otherwise, the event is raised only once, the first time the Interval value elapses.
Если параметр Interval задан после Timer начала работы, счетчик сбрасывается. If Interval is set after the Timer has started, the count is reset. Например, если задать для интервала значение 5 секунд, а затем задать Enabled значение true , счетчик начнется в Enabled заданное время. For example, if you set the interval to 5 seconds and then set Enabled to true , the count starts at the time Enabled is set. Если интервал равен 10 секундам при значении счетчика 3 секунды, Elapsed событие будет вызвано в первый раз за 13 секунд после Enabled установки значения true . If you reset the interval to 10 seconds when count is 3 seconds, the Elapsed event is raised for the first time 13 seconds after Enabled was set to true .
Если SynchronizingObject свойство имеет значение null , Elapsed событие вызывается в ThreadPool потоке. If the SynchronizingObject property is null ,the Elapsed event is raised on a ThreadPool thread. Если обработка Elapsed события длится дольше Interval , это событие может быть вновь вызвано в другом ThreadPool потоке. If the processing of the Elapsed event lasts longer than Interval, the event might be raised again on another ThreadPool thread. В этом случае обработчик событий должен быть повторным. In this situation, the event handler should be reentrant.
Метод обработки событий может выполняться в одном потоке в то же время, когда другой поток вызывает Stop метод или устанавливает Enabled свойство в значение false . The event-handling method might run on one thread at the same time that another thread calls the Stop method or sets the Enabled property to false . Это может привести к Elapsed возникновению события после остановки таймера. This might result in the Elapsed event being raised after the timer is stopped. В примере кода для Stop метода показан один из способов избежать этого состояния гонки. The example code for the Stop method shows one way to avoid this race condition.
Даже если SynchronizingObject параметр не равен null , Elapsed события могут происходить после Dispose Stop вызова метода или после того Enabled , как свойство имеет значение false , поскольку сигнал для вызова Elapsed события всегда находится в очереди на выполнение в потоке пула потоков. Even if SynchronizingObject is not null , Elapsed events can occur after the Dispose or Stop method has been called or after the Enabled property has been set to false , because the signal to raise the Elapsed event is always queued for execution on a thread pool thread. Одним из способов разрешения этого состояния гонки является установка флага, сообщающего обработчику событий о Elapsed пропуске последующих событий. One way to resolve this race condition is to set a flag that tells the event handler for the Elapsed event to ignore subsequent events.
TimerКомпонент перехватывает и подавляет все исключения, вызываемые обработчиками событий для Elapsed события. The Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event. Это поведение может быть изменено в будущих выпусках платформа .NET Framework. This behavior is subject to change in future releases of .NET Framework.
knadh / zsh-elapsed-time.md
Elapsed and execution time display for commands in ZSH
Append this to your
This comment has been minimized.
Copy link Quote reply
kimonoki commented May 18, 2019 •
I get preexec:1: bad math expression: operator expected at `N/1000000′
This comment has been minimized.
Copy link Quote reply
jep-dev commented Jul 13, 2019 •
Just thought I’d post my 2 cents. I think you want date +%s%0N over date+%s%N , unless I’m missing something; otherwise nanoseconds are printed by %N without leading zeroes, independently of the %s. If you’re using nanos as fractional seconds (aka fixed point arithmetic with ns as the atomic unit) the leading zeroes become significant. So for example, 1s+10 8 ns = «1100000000», 1s+10 7 ns = «110000000», . 1s+1ns = «11». (You want 1s+10 8 ns = «1100000000″, 1s+10 7 ns = «1010000000″, . 1s+1ns = «1000000001«.) You can expect 10% of measurements to have at least 1 leading zero in the nanos, and each omitted zero to cause an order of magnitude of error in the total time. Hope this helps!
This comment has been minimized.
Copy link Quote reply
knadh commented Jul 14, 2019
@jep-dev You’re right. Updated the gist. Thank you.
This comment has been minimized.
Copy link Quote reply
knadh commented Jul 14, 2019
@kimonoki Sorry, missed your comment. Unsure about the error.
This comment has been minimized.
Copy link Quote reply
rufreakde commented Aug 13, 2019 •
@kimonoki Getting the same error:
bad math expression: operator expected at ‘N/1000000’
timer=$(($(date +%s%0N)/1000000)) — error
$(($(date +%s)/1000000)) — no error
I am not sure here myself using only %s instead of %s%0N does work for me but nanoseconds throws an error.
Print time in a batch file (milliseconds)
How do I print the time (in ms) in a Windows batch file?
I want to measure the time that passes between lines in my batch file, but Windows’s «time /T» does not print milliseconds.
7 Answers 7
%time% should work, provided enough time has elapsed between calls:
On my system I get the following output:
If you’re doing something like
then you could simply put a setlocal enabledelayedexpansion at the beginning of your batch file and use !time! instead of %time% which gets evaluated on execution, not on parsing the line (which includes complete blocks enclosed in parentheses).
Below batch «program» should do what you want. Please note that it outputs the data in centiseconds instead of milliseconds. The precision of the used commands is only centiseconds.
Here is an example output:
Here is the batch script:
6,2%-100)*100 should be (1%STARTTIME:
6,2%-100)*1000 etc. – Kvant Jun 8 ’14 at 13:31
9,2%-100) should be (1%STARTTIME:
9,2%-100) * 10 etc. – Kvant Jun 8 ’14 at 13:33
Maybe this tool (archived version ) could help? It doesn’t return the time, but it is a good tool to measure the time a command takes.
%TIME% is in the format H:MM:SS,CS after midnight and hence conversion to centiseconds >doesn’t work. Seeing Patrick Cuff’s post with 6:46am it seems that it is not only me.
But with this lines bevor you should will fix that problem easy:
Thanks for your nice inspiration! I like to use it in my mplayer, ffmpeg, sox Scripts to pimp my mediafiles for old PocketPlayers just for fun.
You have to be careful with what you want to do, because it is not just about to get the time.
The batch has internal variables to represent the date and the tme: %DATE% %TIME%. But they dependent on the Windows Locale.
Now, how long your script will work and when? For example, if it will be longer than a day and does pass the midnight it will definitely goes wrong, because difference between 2 timestamps between a midnight is a negative value! You need the date to find out correct distance between days, but how you do that if the date format is not a constant? Things with %DATE% and %TIME% might goes worser and worser if you continue to use them for the math purposes.
The reason is the %DATE% and %TIME% are exist is only to show a date and a time to user in the output, not to use them for calculations. So if you want to make correct distance between some time values or generate some unique value dependent on date and time then you have to use something different and accurate than %DATE% and %TIME%.
I am using the wmic windows builtin utility to request such things (put it in a script file):
or type it in the cmd.exe console:
The disadvantage of this is a slow performance in case of frequent calls. On mine machine it is about 12 calls per second.
If you want to continue use this then you can write something like this (get_datetime.bat):
Now, you can parse %RETURN_VALUE% somethere in your script:
Calculate time difference in Windows batch file
How can I get the difference between two times in a Batch file? Because I want to print it in an HTML file.
I thought this would be possible, but it isn’t.
But what I want is:
Or 9 minutes and 10 seconds or 550 seconds
10 Answers 10
EDIT 2017-05-09: Shorter method added
I developed a shorter method to get the same result, so I couldn’t resist to post it here. The two for commands used to separate time parts and the three if commands used to insert leading zeros in the result are replaced by two long arithmetic expressions, that could even be combined into a single longer line.
The method consists in directly convert a variable with a time in «HH:MM:SS.CC» format into the formula needed to convert the time to centiseconds, accordingly to the mapping scheme given below:
That is, insert (((10 at beginning, replace the colons by %%100)*60+1 , replace the point by %%100)*100+1 and insert %%100 at end; finally, evaluate the resulting string as an arithmetic expression. In the time variable there are two different substrings that needs to be replaced, so the conversion must be completed in two lines. To get an elapsed time, use (endTime)-(startTime) expression and replace both time strings in the same line.
EDIT 2017/06/14: Locale independent adjustment added
EDIT 2020/06/05: Pass-over-midnight adjustment added
You may review a detailed explanation of this method at this answer.
Below batch «program» should do what you want. Please note that it outputs the data in centiseconds instead of milliseconds. The precision of the used commands is only centiseconds.
Here is an example output:
Here is the batch script:
02,2%» is failing here. Nevertheless, this does not work always, the solution from Aacini seems to work better. – Philm Mar 5 ’14 at 11:16
A re-hash of Aacini’s code because most likely you are going to set the start time as a variable and want to save that data for output:
Based on previous answers, here are reusable «procedures» and a usage example for calculating the elapsed time:
Fixed Gynnad’s leading 0 Issue. I fixed it with the two Lines
Full Script ( CalculateTime.cmd ):
Aacini’s latest code showcases an awesome variable substitution method.
It’s a shame it’s not Regional format proof — it fails on so many levels.
Here’s a short fix that keeps the substitution+math method intact:
«Lean and Mean» TIMER with Regional format, 24h and mixed input support
Adapting Aacini’s substitution method body, no IF’s, just one FOR (my regional fix)
1: File timer.bat placed somewhere in %PATH% or the current dir
Usage:
timer & echo start_cmds & timeout /t 3 & echo end_cmds & timer
timer & timer «23:23:23,00»
timer «23:23:23,00» & timer
timer «13.23.23,00» & timer «03:03:03.00»
timer & timer «0:00:00.00» no & cmd /v:on /c echo until midnight=!timer_end!
Input can now be mixed, for those unlikely, but possible time format changes during execution
2: Function :timer bundled with the batch script (sample usage below):
:: to test it, copy-paste both above and below code sections
Here is my attempt to measure time difference in batch.
It respects the regional format of %TIME% without taking any assumptions on type of characters for time and decimal separators.
The code is commented but I will also describe it here.
It is flexible so it can also be used to normalize non-standard time values as well
The main function :timediff
Example:
Explanation of the :timediff function:
Input and output format is the same format as %TIME%
It takes 3 parameters from left to right:
Param1: Name of the environment variable to save the result to.
Param2: Name of the environment variable to be passed to the function containing StartTime string
Param3: Name of the environment variable to be passed to the function containing EndTime string
If EndTime is less than StartTime then:
- EndTime will be treated as a time in the next day
in that case, the function measures time difference between a maximum distance of 24 hours minus 1 centisecond
time elements can have values greater than their standard maximum value ex: 12:247:853.5214
provided than the total represented time does not exceed 24*360000 centiseconds or (24:00:00.00) otherwise the result will not be meaningful.
If EndTime is greater than or equals to StartTime then:
- No formal limitation applies to the value of elements,
except that total represented time can not exceed 2147483647 centiseconds.
More examples with literal and non-standard time values
- Literal example with EndTime less than StartTime:
- Output:
- Normalize non-standard time:
- Output:
- Last bonus example:
- Output: