Windows command line command time

my code gives you the running time in milliseconds, up to 24 hrs, it is locale insensitive, and accounts for negative values if code runs through midnight. it uses delayed expansion, and should be saved in a cmd/bat file.

before your code:

SETLOCAL EnableDelayedExpansion

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set t=%%I
set /a t1 = %t:~8,1%*36000 + %t:~9,1%*3600 + %t:~10,1%*600 + %t:~11,1%*60 + %t:~12,1%*10 + %t:~13,1% && set t1=!t1!%t:~15,3%

after your code:

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set t=%%I
set /a t2 = %t:~8,1%*36000 + %t:~9,1%*3600 + %t:~10,1%*600 + %t:~11,1%*60 + %t:~12,1%*10 + %t:~13,1% && set t2=!t2!%t:~15,3%
set /a t2-=t1 && if !t2! lss 0 set /a t2+=24*3600000

if you want running time in HH:mm:ss.000 format, add:

set /a "h=t2/3600000,t2%%=3600000,m=t2/60000,t2%%=60000" && set t2=00000!t2!&& set t2=!t2:~-5!
if %h% leq 9 (set h=0%h%) && if %m% leq 9 (set m=0%m%)
set t2=%h%:%m%:%t2:~0,2%.%t2:~2,3%

ENDLOCAL

variable t2 holds your running time, you can echo %t2% to display it.

Attempt 1

Using prompt $t$g (as in the currently accepted answer) results in a prompt as in this example:

14:32:46,28>

Attempt 2

Using prompt $P - $T$H$H$H$G (as in the previously posted answer) results in a prompt like in this example:

C:\Users\Pierre.Vriens - 14:32:46>

Attempt 3

Using prompt $T$H$H$H$H$H$H$G (as mentioned also in a comment from OPer below the currently accepted answer) results in a prompt like in this example:

14:33>

So it looks like this attempt (= nr 3) is the correct answer … (Credits: Daniel Williams), because:

  • $T results in 14:32:46,28.
  • $H$H$H$H$H$H performs, 6 times, a backspace (i.e. removes the :46,28 part of that).
  • $G adds > to it again.

This post explains how to get current date and time from command prompt or in a batch file.

How to get date and time in a batch file

Below is a sample batch script which gets current date and time
Datetime.cmd

@echo off

for /F "tokens=2" %%i in ('date /t') do set mydate=%%i
set mytime=%time%
echo Current time is %mydate%:%mytime%

When we run the above batch file

C:\>datetime.cmd
Current time is 08/12/2015:22:57:24.62
C:\>

Get date from command line

To print today’s date on the command prompt, we can run date /t.

c:\>date /t
Thu 05/14/2015
c:\>

Just running date without any arguments prints the current date and then prompts to enter a new date if the user wants to reset it.

c:\>date
The current date is: Sat 05/16/2015
Enter the new date: (mm-dd-yy)
c:\>

In addition to date command, we also have an environment variable using which we can find today’s date.

c:\>echo %date%
Sun 05/17/2015

How to get only the date in MM/DD/YYYY format?

You may want to exclude the day (like ‘Sun’ in the above example) and print only the date in MM/DD/YYYY format. The below command works for the same.

for /F "tokens=2" %i in ('date /t') do echo %i

Example:

c:\>for /F "tokens=2" %i in ('date /t') do echo %i
05/14/2015
c:\>

Get time from command prompt

Similar to date command, we have the command time which lets us find the current system time. Some examples below.

c:\>time /t
11:17 PM

c:\>time
The current time is: 23:17:18.57
Enter the new time:
c:\>

As you can see, the command prints the time in different formats. It prints in 12 hour format when /t is added and in 24 hours format without /t

We can also get the current time from environment variables.

c:\>echo %time%
23:23:51.62
c:\>

Get date and time

c:\>echo  %date%-%time%
Sun 05/17/2015-23:21:03.34


Download Article


Download Article

This wikiHow teaches you how to change your time and date on a computer running the Windows operating system using the Command Prompt app.

  1. Image titled Change the Computer Time and Date Using the Command Prompt Step 1

    1

    Understand why this is necessary. While you can change your computer’s time and date with Command Prompt while your computer’s automatic time and date is active, your computer will eventually reset its time and date to match the current one.

    • In some cases, your computer will reset the time and date as soon as you close Command Prompt.
  2. Image titled Change the Computer Time and Date Using the Command Prompt Step 2

    2

    Open Start

    Windows Start

    . Click the Windows logo in the bottom-left corner of the screen.

    Advertisement

  3. Image titled Change the Computer Time and Date Using the Command Prompt Step 3

    3

    Open Settings

    Windows Settings

    . Click the gear-shaped icon in the lower-left corner of the Start window. This will prompt the Settings window to appear.

  4. Image titled Change the Computer Time and Date Using the Command Prompt Step 4

    4

    Click Time & Language. This option is in the middle of the Settings window.

  5. Image titled Change the Computer Time and Date Using the Command Prompt Step 5

    5

    Click Date & time. It’s a tab in the upper-left side of the window.

  6. Image titled Change the Computer Time and Date Using the Command Prompt Step 6

    6

    Click the colored «Set time automatically» switch

    Windows Switch On

    . The switch will turn grey

    Windows Switch Off

    , indicating that Windows will no longer attempt to reset the time and date automatically. At this point, you’re free to change your computer’s time and date in Command Prompt.

  7. Advertisement

  1. Image titled Change the Computer Time and Date Using the Command Prompt Step 7

    1

    Open Start

    Windows Start

    . Click the Windows logo in the bottom-left corner of the screen. The Start menu will pop up.

  2. Image titled Change the Computer Time and Date Using the Command Prompt Step 8

    2

    Search for Command Prompt. Type in command prompt, then wait for Command Prompt to appear at the top of the Start menu.

  3. Image titled Change the Computer Time and Date Using the Command Prompt Step 9

    3

    Right-click

    Windows cmd

    Command Prompt. It’s at the top of the Start menu. A drop-down menu will appear.

    • If your mouse doesn’t have a right-click button, click the right side of the mouse, or use two fingers to click the mouse.
    • If your computer uses a trackpad instead of a mouse, use two fingers to tap the trackpad or press the bottom-right side of the trackpad.
  4. Image titled Change the Computer Time and Date Using the Command Prompt Step 10

    4

    Click Run as administrator. This option is in the drop-down menu.

    • You can’t change your computer’s time and date without administrator privileges.
  5. Image titled Change the Computer Time and Date Using the Command Prompt Step 11

    5

    Click Yes when prompted. Doing so confirms that you want to open Command Prompt; you should see the Command Prompt window appear at this point.

  6. Image titled Change the Computer Time and Date Using the Command Prompt Step 12

    6

    Change the time. The command for changing time in Command Prompt is time HH:MM:SS AM/PM where «HH:MM:SS» refers to the hour, minute, and second, and «AM/PM» refers to whether it’s morning or afternoon. To change your computer’s time, type in this command with your preferred time indicated, then press Enter.

    • For example, typing in time 08:35:00 AM and pressing Enter would change your computer’s time to 8:35 AM.
    • To change the time to 10:00 PM, you would type in time 10:00:00 PM and press Enter.
    • If you’re comfortable with 24-hour time, you can type in your preferred time (e.g., 14:00:00 for 2:00 PM) and leave off the «AM» or «PM» tag.
  7. Image titled Change the Computer Time and Date Using the Command Prompt Step 13

    7

    Change the date. The date format you’ll use in Command Prompt depends on your country, but Command Prompt will tell you which format to use: type in date and press Enter, then type in the date you want to use in whichever format is specified by Command Prompt (e.g., «mm-dd-yyyy» in the United States) and press Enter.

    • To change a United States computer’s date to September 25th, 2018, you would type in date and press Enter, then type in 09-25-2018 and press Enter.
    • To adjust the date to read October 12th, 2018 on a European computer, you would type in date and press Enter, then enter either 12-10-2018 or 2018-10-12 depending on your location.
  8. Image titled Change the Computer Time and Date Using the Command Prompt Step 14

    8

    Review your computer’s time and date. In the bottom-right corner of the screen, you should see both your updated time and your updated date reflected in your region’s format.

    • If you use 24-hour time, you won’t see «AM» or «PM» listed here.
  9. Advertisement

Add New Question

  • Question

    I tried to change the time on my computer by using the command prompt, but it didn’t work. What can I do?

    Community Answer

    Try right clicking on the CMD icon and selecting «Run as administrator.» Then follow the instructions again.

  • Question

    Can I change system time without administrator privileges?

    JLloyd

    Unfortunately, you can’t—attempting to change the time and/or date without using Command Prompt in administrator mode will result in an error.

  • Question

    What if I want to set date and time settings as automatic so that it fetches the date and time from the internet?

    JLloyd

    Your computer already does this by default. If you turned off the automatic time and date setting, you can re-enable it from within Windows Settings by opening the Time & Language menu and clicking the «Off» switch next to the «Set time automatically» heading.

See more answers

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

  • As long as you leave the automatic time and date feature disabled, your new time and date won’t change back when you restart your computer.

Thanks for submitting a tip for review!

Advertisement

  • Changing the date to a past one may interfere with some programs and security on your computer.

Advertisement

About This Article

Article SummaryX

1. Disable automatic date and time first.
2. Open the command prompt as an administrator.
3. Type «time» and press the space bar.
4. Enter the time in this format: 08:35:00 AM.
5. Press Enter.
6. Type «date» and press Enter.
7. Enter the date in the preferred format (e.g., MM-DD-YYYY).
8. Press Enter.

Did this summary help you?

Thanks to all authors for creating a page that has been read 555,319 times.

Is this article up to date?

  • Home
  • Question

  • How do I measure execution time of a command on the Windows command line?

Is there a built-in way to measure execution time of a command on the Windows command line?

This question is related to
windows
batch-file
time
cmd
windows-server-2003

The answer is


PowerShell has a cmdlet for this called Measure-Command. You’ll have to ensure that PowerShell is available on the machine that runs it.

PS> Measure-Command { echo hi }

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 0
Ticks             : 1318
TotalDays         : 1.52546296296296E-09
TotalHours        : 3.66111111111111E-08
TotalMinutes      : 2.19666666666667E-06
TotalSeconds      : 0.0001318
TotalMilliseconds : 0.1318

Measure-Command captures the command’s output. You can redirect the output back to your console using Out-Default:

PS> Measure-Command { echo hi | Out-Default }
hi

Days              : 0
...

Measure-Command returns a TimeSpan object, so the measured time is printed as a bunch of fields. You can format the object into a timestamp string using ToString():

PS> (Measure-Command { echo hi | Out-Default }).ToString()
hi
00:00:00.0001318

If the command inside Measure-Command changes your console text color, use [Console]::ResetColor() to reset it back to normal.


If you want

  1. To measure execution time down to the hundredth of a second in (hh:mm:ss.ff format)
  2. To not have to download and install a resource pack
  3. To look like a huge DOS nerd (who doesn’t)

Try copying the following script into a new batch file (e.g. timecmd.bat):

@echo off
@setlocal

set start=%time%

:: Runs your command
cmd /c %*

set end=%time%
set options="tokens=1-4 delims=:.,"
for /f %options% %%a in ("%start%") do set start_h=%%a&set /a start_m=100%%b %% 100&set /a start_s=100%%c %% 100&set /a start_ms=100%%d %% 100
for /f %options% %%a in ("%end%") do set end_h=%%a&set /a end_m=100%%b %% 100&set /a end_s=100%%c %% 100&set /a end_ms=100%%d %% 100

set /a hours=%end_h%-%start_h%
set /a mins=%end_m%-%start_m%
set /a secs=%end_s%-%start_s%
set /a ms=%end_ms%-%start_ms%
if %ms% lss 0 set /a secs = %secs% - 1 & set /a ms = 100%ms%
if %secs% lss 0 set /a mins = %mins% - 1 & set /a secs = 60%secs%
if %mins% lss 0 set /a hours = %hours% - 1 & set /a mins = 60%mins%
if %hours% lss 0 set /a hours = 24%hours%
if 1%ms% lss 100 set ms=0%ms%

:: Mission accomplished
set /a totalsecs = %hours%*3600 + %mins%*60 + %secs%
echo command took %hours%:%mins%:%secs%.%ms% (%totalsecs%.%ms%s total)

Usage

If you put timecmd.bat in a directory in your path, you can call it from anywhere like this:

timecmd [your command]

E.g.

C:\>timecmd pause
Press any key to continue . . .
command took 0:0:1.18

If you want to do output redirection, you can quote the command like this:

timecmd "dir c:\windows /s > nul"

This should handle commands that run from before- to after-midnight, but the output will be wrong if your command runs for 24 hours or more.


Hehe, the most simple solution might be this:

echo %time%
YourApp.exe
echo %time%

This works on every Windows out of the box.


In case of an application using console output, it might be convenient to store the starting time in a temporary variable:

set startTime=%time%
YourApp.exe
echo Start Time: %startTime%
echo Finish Time: %time%

Just a little expansion of the answer from Casey.K about using the Measure-Command from PowerShell:

  1. You can invoke PowerShell from the standard command prompt, like this:

    powershell -Command "Measure-Command {echo hi}"
    
  2. This will eat the standard output, but you can prevent that by adding | Out-Default like this from PowerShell:

    Measure-Command {echo hi | Out-Default}
    

    Or from a command prompt:

    powershell -Command "Measure-Command {echo hi | Out-Default}"
    

Of course, you’re free to wrap this in a script file *.ps1 or *.bat.


The one-liner I use in Windows Server 2008 R2 is:

cmd /v:on /c "echo !TIME! & *mycommand* & echo !TIME!"

So long as mycommand doesn’t require quotes (which screws with cmd’s quote processing). The /v:on is to allow for the two different TIME values to be evaluated independently rather than once at the execution of the command.


If you have a command window open and call the commands manually, you can display a timestamp on each prompt, e.g.

prompt $d $t $_$P$G

It gives you something like:

23.03.2009 15:45:50,77

C:\>

If you have a small batch script that executes your commands, have an empty line before each command, e.g.

(empty line)

myCommand.exe

(next empty line)

myCommand2.exe

You can calculate the execution time for each command by the time information in the prompt. The best would probably be to pipe the output to a textfile for further analysis:

MyBatchFile.bat > output.txt

Since others are recommending installing things like freeware and PowerShell, you could also install Cygwin, which would give you access to many basic Unix commands like time:

abe@abe-PC:~$ time sleep 5

real    0m5.012s
user    0m0.000s
sys 0m0.000s

Not sure how much overhead Cygwin adds.


Not quite as elegant as some of the functionality on Unix, but create a cmd file which looks like:

@echo off
time < nul
yourexecutable.exe > c:\temp\output.txt
time < nul
rem on newer windows system you can try time /T

That will display the start and stop times like so:

The current time is: 10:31:57.92
Enter the new time:
The current time is: 10:32:05.94
Enter the new time:

I use freeware called «GS Timer».

Just make a batch file like this:

timer
yourapp.exe
timer /s

If you need a set of times, just pipe the output of timer /s into a .txt file.

You can get it here: Gammadyne’s Free DOS Utilities


The resolution is 0.1 seconds.


I’m using Windows XP and for some reason timeit.exe does not work for me. I found another alternative — PTIME. This works very well.

http://www.pc-tools.net/win32/ptime/

Example —

C:\> ptime

ptime 1.0 for Win32, Freeware - http://www.pc-tools.net/
Copyright(C) 2002, Jem Berkes <[email protected]>

Syntax: ptime command [arguments ...]

ptime will run the specified command and measure the execution time
(run time) in seconds, accurate to 5 millisecond or better. It is an
automatic process timer, or program timer.


C:\> ptime cd

ptime 1.0 for Win32, Freeware - http://www.pc-tools.net/
Copyright(C) 2002, Jem Berkes <jbe[email protected]>

===  cd ===
C:\

Execution time: 0.015 s

There’s also TimeMem (March 2012):

This is a Windows utility which executes a program and displays its
execution time, memory usage, and IO statistics. It is similar in
functionality to the Unix time utility.


As long as it doesn’t last longer than 24hours…

@echo off

set starttime=%TIME%
set startcsec=%STARTTIME:~9,2%
set startsecs=%STARTTIME:~6,2%
set startmins=%STARTTIME:~3,2%
set starthour=%STARTTIME:~0,2%
set /a starttime=(%starthour%*60*60*100)+(%startmins%*60*100)+(%startsecs%*100)+(%startcsec%)

:TimeThis
ping localhost 

set endtime=%time%
set endcsec=%endTIME:~9,2%
set endsecs=%endTIME:~6,2%
set endmins=%endTIME:~3,2%
set endhour=%endTIME:~0,2%
if %endhour% LSS %starthour% set /a endhour+=24
set /a endtime=(%endhour%*60*60*100)+(%endmins%*60*100)+(%endsecs%*100)+(%endcsec%)

set /a timetaken= ( %endtime% - %starttime% )
set /a timetakens= %timetaken% / 100
set timetaken=%timetakens%.%timetaken:~-2%

echo.
echo Took: %timetaken% sec.

Here is a

Postfix timer version:

Usage example:

timeout 1 | TimeIt.cmd

Execution took  ~969 milliseconds.

Copy & paste this into some editor like for example Notepad++ and save it as TimeIt.cmd:

:: --- TimeIt.cmd ----
    @echo off
    setlocal enabledelayedexpansion

    call :ShowHelp

    :: Set pipeline initialization time
    set t1=%time%

    :: Wait for stdin
    more

    :: Set time at which stdin was ready
    set t2=!time!


    :: Calculate difference
    Call :GetMSeconds Tms1 t1
    Call :GetMSeconds Tms2 t2

    set /a deltaMSecs=%Tms2%-%Tms1%
    echo Execution took ~ %deltaMSecs% milliseconds.

    endlocal
goto :eof

:GetMSeconds
    Call :Parse        TimeAsArgs %2
    Call :CalcMSeconds %1 %TimeAsArgs%

goto :eof

:CalcMSeconds
    set /a %1= (%2 * 3600*1000) + (%3 * 60*1000) + (%4 * 1000) + (%5)
goto :eof

:Parse

    :: Mask time like " 0:23:29,12"
    set %1=!%2: 0=0!

    :: Replace time separators with " "
    set %1=!%1::= !
    set %1=!%1:.= !
    set %1=!%1:,= !

    :: Delete leading zero - so it'll not parsed as octal later
    set %1=!%1: 0= !
goto :eof

:ShowHelp
    echo %~n0 V1.0 [Dez 2015]
    echo.
    echo Usage: ^<Command^> ^| %~nx0
    echo.
    echo Wait for pipe getting ready... :)
    echo  (Press Ctrl+Z ^<Enter^> to Cancel)
goto :eof

^ — Based on ‘Daniel Sparks’ Version


Depending on the version of Windows you’re using, just running bash will put you into Bash mode. This will allow you to use a bunch of commands that are not available on PowerShell directly (like the time command). Timing your command is now as easy as executing:

# The clause <your-command> (without the angle brackets) denotes the command you want to run.
$ time <your-command>

Note: You can easily quit from Bash mode and return back into your mainstream shell by running exit while in Bash mode.

This worked for me perfectly (Windows 10) after trying out other methods (like Measure-Command) which sometimes produce undesired stats. Hope this works for you as well.


An alternative to measure-time is simply «Get-Date». You don’t have that hassle with forwarding output and so on.

$start = Get-Date
[System.Threading.Thread]::Sleep(1500)
$(Get-Date) - $start

Output:

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 1
Milliseconds      : 506
Ticks             : 15060003
TotalDays         : 1.74305590277778E-05
TotalHours        : 0.000418333416666667
TotalMinutes      : 0.025100005
TotalSeconds      : 1.5060003
TotalMilliseconds : 1506.0003

This is a one-liner which avoids delayed expansion, which could disturb certain commands:

cmd /E /C "prompt $T$$ & echo.%TIME%$ & COMMAND_TO_MEASURE & for %Z in (.) do rem/ "

The output is something like:

14:30:27.58$
...
14:32:43.17$ rem/ 

For long-term tests replace $T by $D, $T and %TIME% by %DATE%, %TIME% to include the date.

To use this inside of a batch file, replace %Z by %%Z.


Update

Here is an improved one-liner (without delayed expansion too):

cmd /E /C "prompt $D, $T$$ & (for %# in (.) do rem/ ) & COMMAND_TO_MEASURE & for %# in (.) do prompt"

The output looks similar to this:

2015/09/01, 14:30:27.58$ rem/ 
...
2015/09/01, 14:32:43.17$ prompt

This approach does not include the process of instancing a new cmd in the result, nor does it include the prompt command(s).


Here is my method, no conversion and no ms. It is useful to determine encoding durations (limited to 24 hours though):

@echo off

:start
REM Start time storage
set ST=%time%
echo Process started at %ST%
echo.
echo.

REM Your commands
REM Your commands
REM Your commands

:end
REM Start Time Definition
for /f "tokens=1-3 delims=:" %%a in ("%ST%") do set /a h1=%%a & set /a m1=%%b & set /a s1=%%c

REM End Time Definition
for /f "tokens=1-3 delims=:" %%a in ("%TIME%") do set /a h2=%%a & set /a m2=%%b & set /a s2=%%c

REM Difference
set /a h3=%h2%-%h1% & set /a m3=%m2%-%m1% & set /a s3=%s2%-%s1%

REM Time Adjustment
if %h3% LSS 0 set /a h3=%h3%+24
if %m3% LSS 0 set /a m3=%m3%+60 & set /a h3=%h3%-1
if %s3% LSS 0 set /a s3=%s3%+60 & set /a m3=%m3%-1

echo Start    :    %ST%
echo End    :    %time%
echo.
echo Total    :    %h3%:%m3%:%s3%
echo.
pause

This is a comment/edit to Luke Sampson’s nice timecmd.bat and reply to

For some reason this only gives me output in whole seconds… which for me is useless. I mean that I run timecmd pause, and it always results in 1.00 sec, 2.00 sec, 4.00 sec… even 0.00 sec! Windows 7. – Camilo Martin Sep 25 ’13 at 16:00 «

On some configurations the delimiters may differ. The following change should cover atleast most western countries.

set options="tokens=1-4 delims=:,." (added comma)

The %time% milliseconds work on my system after adding that ‘,’

(*because site doesn’t allow anon comment and doesn’t keep good track of identity even though I always use same guest email which combined with ipv6 ip and browser fingerprint should be enough to uniquely identify without password)


In case anyone else has come here looking for an answer to this question, there’s a Windows API function called GetProcessTimes(). It doesn’t look like too much work to write a little C program that would start the command, make this call, and return the process times.


Another approach with powershell:

@echo off
for /f %%t in ('powershell "(get-date).tofiletime()"') do set mst=%%t

rem some commands

powershell ((get-date).tofiletime() - %mst%)

this will print the execution time in milliseconds.


The answer of driblio can be made a little shorter (though not much readable)

@echo off

:: Calculate the start timestamp
set _time=%time%
set /a _hours=100%_time:~0,2%%%100,_min=100%_time:~3,2%%%100,_sec=100%_time:~6,2%%%100,_cs=%_time:~9,2%
set /a _started=_hours*60*60*100+_min*60*100+_sec*100+_cs


:: yourCommandHere


:: Calculate the difference in cSeconds
set _time=%time%
set /a _hours=100%_time:~0,2%%%100,_min=100%_time:~3,2%%%100,_sec=100%_time:~6,2%%%100,_cs=%_time:~9,2%
set /a _duration=_hours*60*60*100+_min*60*100+_sec*100+_cs-_started

:: Populate variables for rendering (100+ needed for padding)
set /a _hours=_duration/60/60/100,_min=100+_duration/60/100%%60,_sec=100+(_duration/100%%60%%60),_cs=100+_duration%%100

echo Done at: %_time% took : %_hours%:%_min:~-2%:%_sec:~-2%.%_cs:~-2%

::prints something like:
::Done at: 12:37:53,70 took: 0:02:03.55

To the remark of Luke Sampson this version is octal safe, though the task should be completed in 24 hours.


my code gives you the running time in milliseconds, up to 24 hrs, it is locale insensitive, and accounts for negative values if code runs through midnight. it uses delayed expansion, and should be saved in a cmd/bat file.

before your code:

SETLOCAL EnableDelayedExpansion

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set t=%%I
set /a t1 = %t:~8,1%*36000 + %t:~9,1%*3600 + %t:~10,1%*600 + %t:~11,1%*60 + %t:~12,1%*10 + %t:~13,1% && set t1=!t1!%t:~15,3%

after your code:

for /f "tokens=2 delims==" %%I in ('wmic os get localdatetime /format:list') do set t=%%I
set /a t2 = %t:~8,1%*36000 + %t:~9,1%*3600 + %t:~10,1%*600 + %t:~11,1%*60 + %t:~12,1%*10 + %t:~13,1% && set t2=!t2!%t:~15,3%
set /a t2-=t1 && if !t2! lss 0 set /a t2+=24*3600000

if you want running time in HH:mm:ss.000 format, add:

set /a "h=t2/3600000,t2%%=3600000,m=t2/60000,t2%%=60000" && set t2=00000!t2!&& set t2=!t2:~-5!
if %h% leq 9 (set h=0%h%) && if %m% leq 9 (set m=0%m%)
set t2=%h%:%m%:%t2:~0,2%.%t2:~2,3%

ENDLOCAL

variable t2 holds your running time, you can echo %t2% to display it.


Having Perl installed the hires solution available, run:

C:\BATCH>time.pl "echo Fine result"
0.01063
Fine result

STDERR comes before measured seconds

#!/usr/bin/perl -w

use Time::HiRes qw();
my $T0 = [ Time::HiRes::gettimeofday ];

my $stdout = `@ARGV`;

my $time_elapsed = Time::HiRes::tv_interval( $T0 );

print $time_elapsed, "\n";
print $stdout;

The following script uses only «cmd.exe» and outputs the number of milliseconds from the time a pipeline is created to the time that the process preceding the script exits. i.e., Type your command, and pipe the to the script. Example: «timeout 3 | runtime.cmd» should yield something like «2990.» If you need both the runtime output and the stdin output, redirect stdin before the pipe — ex: «dir /s 1>temp.txt | runtime.cmd» would dump the output of the «dir» command to «temp.txt» and would print the runtime to the console.

:: --- runtime.cmd ----
@echo off
setlocal enabledelayedexpansion

:: find target for recursive calls
if not "%1"=="" (
    shift /1
    goto :%1
    exit /b
)

:: set pipeline initialization time
set t1=%time%

:: wait for stdin
more > nul

:: set time at which stdin was ready
set t2=!time!

::parse t1
set t1=!t1::= !
set t1=!t1:.= !
set t1=!t1: 0= !

:: parse t2
set t2=!t2::= !
set t2=!t2:.= !
set t2=!t2: 0= !

:: calc difference
pushd %~dp0
for /f %%i in ('%0 calc !t1!') do for /f %%j in ('%0 calc !t2!') do (
    set /a t=%%j-%%i
    echo !t!
)
popd
exit /b
goto :eof

:calc
set /a t=(%1*(3600*1000))+(%2*(60*1000))+(%3*1000)+(%4)
echo !t!
goto :eof

endlocal

  1. In the directory where your program is, type notepad mytimer.bat, click ‘yes’ to create a new file.

  2. Paste the code below, replacing YourApp.exe with your program, then save.

    @echo off
    date /t
    time /t
    YourApp.exe
    date /t
    time /t
    
  3. Type mytimer.bat in the command line then press Enter.


@echo off & setlocal

set start=%time%

REM Do stuff to be timed here.
REM Alternatively, uncomment the line below to be able to
REM pass in the command to be timed when running this script.
REM cmd /c %*

set end=%time%

REM Calculate time taken in seconds, to the hundredth of a second.
REM Assumes start time and end time will be on the same day.

set options="tokens=1-4 delims=:."

for /f %options% %%a in ("%start%") do (
    set /a start_s="(100%%a %% 100)*3600 + (100%%b %% 100)*60 + (100%%c %% 100)"
    set /a start_hs=100%%d %% 100
)

for /f %options% %%a in ("%end%") do (
    set /a end_s="(100%%a %% 100)*3600 + (100%%b %% 100)*60 + (100%%c %% 100)"
    set /a end_hs=100%%d %% 100
)

set /a s=%end_s%-%start_s%
set /a hs=%end_hs%-%start_hs%

if %hs% lss 0 (
    set /a s=%s%-1
    set /a hs=100%hs%
)
if 1%hs% lss 100 set hs=0%hs%

echo.
echo  Time taken: %s%.%hs% secs
echo.

Using a sub to return time in hundredths of second

::tiemeit.cmd
@echo off
Setlocal EnableDelayedExpansion

call :clock 

::call your_command  or more > null to pipe this batch after your_command

call :clock

echo %timed%
pause
goto:eof

:clock
if not defined timed set timed=0
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do ( 
set /A timed = "(((1%%a - 100) * 60 + (1%%b - 100)) * 60 + (1%%c - 100))  * 100 + (1%%d - 100)- %timed%"
)
goto:eof

«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

@echo off & rem :AveYo: compact timer function with Regional format, 24-hours and mixed input support
if not defined timer_set (if not "%~1"=="" (call set "timer_set=%~1") else set "timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_end=%~1") else set "timer_end=%TIME: =0%") & setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789" %%i in ("%timer_end%%timer_set%") do (set CE=%%i&set DE=%%k&set CS=%%l&set DS=%%n)
set "TE=!timer_end:%DE%=%%100)*100+1!"     & set "TS=!timer_set:%DS%=%%100)*100+1!"
set/A "T=((((10!TE:%CE%=%%100)*60+1!%%100)-((((10!TS:%CS%=%%100)*60+1!%%100)" & set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60+100,T/=60,mm=T%%60+100,hh=T/60+100"
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss:~1!%DE%!cc:~1!" & if "%~2"=="" echo/!value!
endlocal & set "timer_end=%value%" & set "timer_set=" & goto :eof

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):

@echo off
set "TIMER=call :timer" & rem short macro
echo.
echo EXAMPLE:
call :timer
timeout /t 3 >nul & rem Any process here..
call :timer
echo.
echo SHORT MACRO:
%TIMER% & timeout /t 1 & %TIMER% 
echo.
echo TEST INPUT:
set "start=22:04:04.58"
set "end=04.22.44,22"
echo %start% ~ start & echo %end% ~ end
call :timer "%start%"
call :timer "%end%"
echo.
%TIMER% & %TIMER% "00:00:00.00" no 
echo UNTIL MIDNIGHT: %timer_end%
echo.
pause 
exit /b

:: to test it, copy-paste both above and below code sections

rem :AveYo: compact timer function with Regional format, 24-hours and mixed input support 
:timer Usage " call :timer [input - optional] [no - optional]" :i Result printed on second call, saved to timer_end 
if not defined timer_set (if not "%~1"=="" (call set "timer_set=%~1") else set "timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_end=%~1") else set "timer_end=%TIME: =0%") & setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789" %%i in ("%timer_end%%timer_set%") do (set CE=%%i&set DE=%%k&set CS=%%l&set DS=%%n)
set "TE=!timer_end:%DE%=%%100)*100+1!"     & set "TS=!timer_set:%DS%=%%100)*100+1!"
set/A "T=((((10!TE:%CE%=%%100)*60+1!%%100)-((((10!TS:%CS%=%%100)*60+1!%%100)" & set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60+100,T/=60,mm=T%%60+100,hh=T/60+100"
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss:~1!%DE%!cc:~1!" & if "%~2"=="" echo/!value!
endlocal & set "timer_end=%value%" & set "timer_set=" & goto :eof

CE,DE and CS,DS stand for colon end, dot end and colon set, dot set — used for mixed format support


The following script emulates *nix epoch time, but it is local and regional. It should handle calender edge cases including leap years. If Cygwin is available, epoch values can be compared by specifying the Cygwin option.

I’m in EST and the difference reported is 4 hours which is relatively correct. There are some interesting solutions to remove the TZ and regional dependencies, but nothing trivial that I noticed.

@ECHO off
SETLOCAL EnableDelayedExpansion

::
::  Emulates local epoch seconds
::

:: Call passing local date and time
CALL :SECONDS "%DATE%" "%TIME%"
IF !SECONDS! LEQ 0 GOTO END

:: Not testing - print and exit
IF NOT "%~1"=="cygwin" (
    ECHO !SECONDS!
    GOTO END
)

:: Call on Cygwin to get epoch time
FOR /F %%c IN ('C:\cygwin\bin\date +%%s') DO SET EPOCH=%%c

:: Show the results
ECHO Local Seconds: !SECONDS!
ECHO Epoch Seconds: !EPOCH!

:: Calculate difference between script and Cygwin
SET /A HOURS=(!EPOCH!-!SECONDS!)/3600
SET /A FRAC=(!EPOCH!-!SECONDS!)%%3600

:: Delta hours shown reflect TZ
ECHO Delta Hours: !HOURS! Remainder: !FRAC!

GOTO END

:SECONDS
SETLOCAL  EnableDelayedExpansion

    :: Expecting values from caller
    SET DATE=%~1
    SET TIME=%~2

    :: Emulate Unix epoch time without considering TZ
    SET "SINCE_YEAR=1970"

    :: Regional constraint! Expecting date and time in the following formats:
    ::   Sun 03/08/2015   Day MM/DD/YYYY
    ::   20:04:53.64         HH:MM:SS
    SET VALID_DATE=0
    ECHO !DATE! | FINDSTR /R /C:"^... [0-9 ][0-9]/[0-9 ][0-9]/[0-9][0-9][0-9][0-9]" > nul && SET VALID_DATE=1
    SET VALID_TIME=0
    ECHO !TIME! | FINDSTR /R /C:"^[0-9 ][0-9]:[0-9 ][0-9]:[0-9 ][0-9]" > nul && SET VALID_TIME=1
    IF NOT "!VALID_DATE!!VALID_TIME!"=="11" (
        IF !VALID_DATE! EQU 0  ECHO Unsupported Date value: !DATE! 1>&2
        IF !VALID_TIME! EQU 0  ECHO Unsupported Time value: !TIME! 1>&2
        SET SECONDS=0
        GOTO SECONDS_END
    )

    :: Parse values
    SET "YYYY=!DATE:~10,4!"
    SET "MM=!DATE:~4,2!"
    SET "DD=!DATE:~7,2!"
    SET "HH=!TIME:~0,2!"
    SET "NN=!TIME:~3,2!"
    SET "SS=!TIME:~6,2!"
    SET /A YEARS=!YYYY!-!SINCE_YEAR!
    SET /A DAYS=!YEARS!*365

    :: Bump year if after February  - want leading zeroes for this test
    IF "!MM!!DD!" GEQ "0301" SET /A YEARS+=1

    :: Remove leading zeros that can cause octet probs for SET /A
    FOR %%r IN (MM,DD,HH,NN,SS) DO (
        SET "v=%%r"
        SET "t=!%%r!"
        SET /A N=!t:~0,1!0
        IF 0 EQU !N! SET "!v!=!t:~1!"
    )

    :: Increase days according to number of leap years
    SET /A DAYS+=(!YEARS!+3)/4-(!SINCE_YEAR!%%4+3)/4

    :: Increase days by preceding months of current year
    FOR %%n IN (31:1,28:2,31:3,30:4,31:5,30:6,31:7,31:8,30:9,31:10,30:11) DO (
        SET "n=%%n"
        IF !MM! GTR !n:~3! SET /A DAYS+=!n:~0,2!
    )

    :: Multiply and add it all together
    SET /A SECONDS=(!DAYS!+!DD!-1)*86400+!HH!*3600+!NN!*60+!SS!

:SECONDS_END
ENDLOCAL & SET "SECONDS=%SECONDS%"
GOTO :EOF

:END
ENDLOCAL

A solution using pure PHP for cmd and one env. variable:

@echo off
setlocal enableextensions

REM set start time env var
FOR /F "tokens=* USEBACKQ" %%F IN (`php -r "echo microtime(true);"`) DO ( SET start_time=%%F )

## PUT_HERE_THE_COMMAND_TO_RUN ##

REM echo elapsed time
php -r "echo 'elapsed: ' . (round(microtime(true) - trim(getenv('start_time')), 2)) . ' seconds' . mb_convert_encoding('&#13;&#10;', 'UTF-8', 'HTML-ENTITIES');"
  • no need for cygwin or non-trusted utilities. Usefull when PHP is locally available

  • precision and output format can be easily tweaked

  • the same idea can be ported for PowerShell


Questions with windows tag:

«Permission Denied» trying to run Python on Windows 10
A fatal error occurred while creating a TLS client credential. The internal error state is 10013
How to install OpenJDK 11 on Windows?
I can’t install pyaudio on Windows? How to solve «error: Microsoft Visual C++ 14.0 is required.»?
git clone: Authentication failed for <URL>
How to avoid the «Windows Defender SmartScreen prevented an unrecognized app from starting warning»
XCOPY: Overwrite all without prompt in BATCH
Laravel 5 show ErrorException file_put_contents failed to open stream: No such file or directory
how to open Jupyter notebook in chrome on windows
Tensorflow import error: No module named ‘tensorflow’
git clone error: RPC failed; curl 56 OpenSSL SSL_read: SSL_ERROR_SYSCALL, errno 10054
bash: npm: command not found?
Anaconda Installed but Cannot Launch Navigator
AttributeError: module ‘cv2.cv2’ has no attribute ‘createLBPHFaceRecognizer’
How to install pandas from pip on windows cmd?
‘ls’ in CMD on Windows is not recognized
Copy Files from Windows to the Ubuntu Subsystem
Tensorflow r1.0 : could not a find a version that satisfies the requirement tensorflow
Kill tomcat service running on any port, Windows
python pip on Windows — command ‘cl.exe’ failed
How to install pip3 on Windows?
Mount current directory as a volume in Docker on Windows 10
Specifying Font and Size in HTML table
Why Local Users and Groups is missing in Computer Management on Windows 10 Home?
Command to run a .bat file
How do I force Robocopy to overwrite files?
Windows- Pyinstaller Error «failed to execute script » When App Clicked
How to completely uninstall Android Studio from windows(v10)?
Docker for Windows error: «Hardware assisted virtualization and data execution protection must be enabled in the BIOS»
How do I kill the process currently using a port on localhost in Windows?
Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443
How to add a custom CA Root certificate to the CA Store used by pip in Windows?
How to reset the use/password of jenkins on windows?
npm ERR! Error: EPERM: operation not permitted, rename
CMD (command prompt) can’t go to the desktop
Xampp-mysql — «Table doesn’t exist in engine» #1932
Change drive in git bash for windows
«OverflowError: Python int too large to convert to C long» on windows but not mac
Visual studio code terminal, how to run a command with administrator rights?
ImportError: cannot import name NUMPY_MKL
Pip — Fatal error in launcher: Unable to create process using ‘»‘
Installing tensorflow with anaconda in windows
Where does Anaconda Python install on Windows?
PermissionError: [Errno 13] Permission denied
How to restart a windows service using Task Scheduler
How to install xgboost in Anaconda Python (Windows platform)?
NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)
Can’t access 127.0.0.1
anaconda — path environment variable in windows
Global npm install location on windows?

Questions with batch-file tag:

‘ls’ is not recognized as an internal or external command, operable program or batch file
» is not recognized as an internal or external command, operable program or batch file
XCOPY: Overwrite all without prompt in BATCH
Can´t run .bat file under windows 10
Execute a batch file on a remote PC using a batch file on local PC
Windows batch — concatenate multiple text files into one
How do I create a shortcut via command-line in Windows?
Getting Error:JRE_HOME variable is not defined correctly when trying to run startup.bat of Apache-Tomcat
Curl not recognized as an internal or external command, operable program or batch file
Best way to script remote SSH commands in Batch (Windows)
Create a batch file to run an .exe with an additional parameter
What does /p mean in set /p?
Find Process Name by its Process ID
Open a Web Page in a Windows Batch FIle
Batch — If, ElseIf, Else
Split text file into smaller multiple text file using command line
Batch script to install MSI
How to ping a server only once from within a batch file?
Command Prompt Error ‘C:\Program’ is not recognized as an internal or external command, operable program or batch file
Difference between xcopy and robocopy
«if not exist» command in batch file
Using a batch to copy from network drive to C: or D: drive
Split string with string as delimiter
BAT file to map to network drive without running as admin
Batch File; List files in directory, only filenames?
Run exe file with parameters in a batch file
Batch script to find and replace a string in text file within a minute for files up to 12 MB
Batch script to find and replace a string in text file without creating an extra output file for storing the modified file
How to solve «The directory is not empty» error when running rmdir command in a batch script?
«npm config set registry https://registry.npmjs.org/» is not working in windows bat file
Difference between IISRESET and IIS Stop-Start command
How to directly execute SQL query in C#?
creating batch script to unzip a file without additional zip tools
How to increment variable under DOS?
Set windows environment variables with a batch file
Executing set of SQL queries using batch file?
Create a txt file using batch file in a specific folder
Run Batch File On Start-up
Checking if a folder exists using a .bat file
Open a URL without using a browser from a batch file
Echo a blank (empty) line to the console from a Windows batch file
Safest way to run BAT file from Powershell script
Batch file to split .csv file
‘adb’ is not recognized as an internal or external command, operable program or batch file
Batch file script to zip files
Redirecting Output from within Batch file
How do I launch a Git Bash window with particular working directory using a script?
How to print the current time in a Batch-File?
How can I use a batch file to write to a text file?
Finding modified date of a file/folder

Questions with time tag:

Date to milliseconds and back to date in Swift
How to manage Angular2 «expression has changed after it was checked» exception when a component property depends on current datetime
how to sort pandas dataframe from one column
Convert time.Time to string
How to get current time in python and break up into year, month, day, hour, minute?
Xcode swift am/pm time to 24 hour format
How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?
What does this format means T00:00:00.000Z?
How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?
Extract time from moment js object
Swift convert unix time to date and time
Python get current time in right timezone
PHP: How to check if a date is today, yesterday or tomorrow
How to parse unix timestamp to time.Time
Python loop to run for certain amount of seconds
Go / golang time.Now().UnixNano() convert to milliseconds?
What is the `zero` value for time.Time in Go?
How to extract epoch from LocalDate and LocalDateTime?
how to sync windows time from a ntp time server in command
Exception in thread «main» java.lang.Error: Unresolved compilation problems
PHP Converting Integer to Date, reverse of strtotime
How to get current time with jQuery
Get current time in hours and minutes
How to format current time using a yyyyMMddHHmmss format?
How to print the current time in a Batch-File?
Should MySQL have its timezone set to UTC?
Checking Date format from a string in C#
Get the time difference between two datetimes
Convert Java string to Time, NOT Date
Creating a timer in python
How do I measure request and response times at once using cURL?
How to delete last item in list?
How do I use .toLocaleTimeString() without displaying seconds?
Converting Milliseconds to Minutes and Seconds?
How to multiply duration by integer?
Oracle date format picture ends before converting entire input string
How to print current date on python3?
Convert java.util.date default format to Timestamp in Java
What is the easiest way to get current GMT time in Unix timestamp format?
Command to get time in milliseconds
Creating java date object from year,month,day
Current date and time as string
how to re-format datetime string in php?
Update TextView Every Second
Current time formatting with Javascript
How to measure time taken between lines of code in python?
Is Android using NTP to sync time?
Getting time difference between two times in PHP
Does Python’s time.time() return the local or UTC timestamp?
PHP: How to get current time in hour:minute:second?

Questions with cmd tag:

‘ls’ is not recognized as an internal or external command, operable program or batch file
» is not recognized as an internal or external command, operable program or batch file
XCOPY: Overwrite all without prompt in BATCH
VSCode Change Default Terminal
How to install pandas from pip on windows cmd?
‘ls’ in CMD on Windows is not recognized
Command to run a .bat file
VMware Workstation and Device/Credential Guard are not compatible
How do I kill the process currently using a port on localhost in Windows?
how to run python files in windows command prompt?
CMD (command prompt) can’t go to the desktop
NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)
What is the reason for the error message «System cannot find the path specified»?
Execute a batch file on a remote PC using a batch file on local PC
How to split large text file in windows?
PHP is not recognized as an internal or external command in command prompt
Change directory in Node.js command prompt
How to disable Hyper-V in command line?
How do I create a shortcut via command-line in Windows?
Windows equivalent of ‘touch’ (i.e. the node.js way to create an index.html)
How to run Pip commands from CMD
Curl not recognized as an internal or external command, operable program or batch file
Windows CMD command for accessing usb?
Create a batch file to run an .exe with an additional parameter
Find Process Name by its Process ID
Set proxy through windows command line including login parameters
Open a Web Page in a Windows Batch FIle
find path of current folder — cmd
Can’t check signature: public key not found
Running CMD command in PowerShell
Ping with timestamp on Windows CLI
The filename, directory name, or volume label syntax is incorrect inside batch
PowerShell The term is not recognized as cmdlet function script file or operable program
«if not exist» command in batch file
Windows 7 — ‘make’ is not recognized as an internal or external command, operable program or batch file
Using a batch to copy from network drive to C: or D: drive
Split string with string as delimiter
«Could not find or load main class» Error while running java program using cmd prompt
Find Number of CPUs and Cores per CPU using Command Prompt
Set windows environment variables with a batch file
Executing set of SQL queries using batch file?
CMD what does /im (taskkill)?
How to run a command in the background on Windows?
How to run different python versions in cmd
Open a URL without using a browser from a batch file
How to fix ‘.’ is not an internal or external command error
Redirecting Output from within Batch file
UTF-8 in Windows 7 CMD
How to copy a folder via cmd?
Basic text editor in command prompt?

Questions with windows-server-2003 tag:

Multiple -and -or in PowerShell Where-Object statement
Batch file to restart a service. Windows
Error message: (provider: Shared Memory Provider, error: 0 — No process is on the other end of the pipe.)
Domain Account keeping locking out with correct password every few minutes
What possibilities can cause «Service Unavailable 503» error?
ORA-12505: TNS:listener does not currently know of SID given in connect descriptor (DBD ERROR: OCIServerAttach)
how to get list of port which are in use on the server
How do I ‘svn add’ all unversioned files to SVN?
Windows command to get service status?
How do I measure execution time of a command on the Windows command line?
How do I determine if a port is open on a Windows server?
How can a windows service programmatically restart itself?
Apache and IIS side by side (both listening to port 80) on windows2003

  • Windows cannot complete the extraction
  • Windows command line command list
  • Windows cannot be installed to this disk the selected disk is of the gpt
  • Windows command line clear command
  • Windows cmd open windows explorer