I am usually using
echo.|time & my_command & echo.|time
when I have nothing else at hand. This causes output like the following:
> echo.|time & ping -n 4 localhost > nul & echo.|time
The current time is: 18:42:34,63
Enter the new time:
The current time is: 18:42:37,68
Enter the new time:
Not pretty and can be made prettier by piping to findstr:
echo.|time|findstr current & ping -n 4 localhost > nul & echo.|time|findstr current
If you have delayed expansion enabled by default (or started cmd with /v:on
as argument) you can also just use echo !time!
without having to resort to ugly hacks with input redirection.
If you want to use a batch file, you can do it like this:
@echo Start time: %time%
@%*>nul 2>nul
@echo End time: %time%
I have added redirection to nul for both stdout and stderr here, because otherwise it might be difficult to find the start and end lines. You may remove this if this is of no concern to you.
But nowadays I mostly use TimeThis – which by now was removed, sadly.
PowerShell offers a way as well:
Measure-Command { my_command }
but you need to be careful with things that rely on the working directory or redirection. For those to work correctly you might need a little trickery:
@echo off
setlocal enableextensions
rem Prepare current directory and command line so they
rem can be stuck into a single-quoted PowerShell string.
set "Dir=%CD:'=''%"
set "Cmd=%*"
set "Cmd=%Cmd:'=''%"
rem Prepare command to pass to PowerShell
set Command=
set "Command=&{"
set "Command=%Command% Set-Location '%Dir%'"
set "Command=%Command%; [Environment]::CurrentDirectory = '%Dir%'"
set "Command=%Command%; $start = Get-Date"
set "Command=%Command%; Write-Host ' Command line : %Cmd%'"
set "Command=%Command%; Write-Host (' Start time : ' + $start.ToString())"
set "Command=%Command%; Write-Host"
set "Command=%Command%; iex 'cmd /c %Cmd%'"
set "Command=%Command%; $end = Get-Date"
set "Command=%Command%; Write-Host"
set "Command=%Command%; Write-Host ' Command line : %Cmd%'"
set "Command=%Command%; Write-Host (' Start time : ' + $start.ToString())"
set "Command=%Command%; Write-Host (' End time : ' + $end.ToString())"
set "Command=%Command%; Write-Host (' Elapsed time : ' + ($end - $start).ToString())"
set "Command=%Command%; }"
powershell -noprofile -command "%Command%"
endlocal
This can be run the same way as timethis
, be sure to escape double quotes with \"
if they are needed in the command line (same as timethis
as well). The output produced is similar. Redirections won't work, though.