How to Measure Execution Time of a Command on the Windows Command Line ⏱️💻
You’re at the command line, executing a complex command, and you wonder, «How long is this going to take?». This is a common question, and fortunately, there are several ways to measure the execution time of a command on the Windows command line. Let’s explore some easy solutions to this problem! 😊
Option 1: Using the timeit
Command
Windows command line provides a built-in command called timeit
that can measure the execution time of any command you run. Simply prefix your command with timeit
and it will display the elapsed time once the command completes.
Here’s an example:
timeit my-command
The output will provide you with the precise time taken by your command to execute. It’s that simple! ⏳
Option 2: Using the PowerShell cmdlet Measure-Command
If you prefer using PowerShell, you can utilize the Measure-Command
cmdlet. This cmdlet calculates the duration of the specified script block.
Here’s an example:
Measure-Command { my-command }
Once executed, the output will include detailed information about the time taken by your command. 🚀
Option 3: Manually Calculating Execution Time
In case you prefer a more hands-on approach, you can manually calculate the execution time using batch scripting or PowerShell scripting.
For Batch scripting, you can use the time
command to capture the current time before and after executing your command. Subtracting these two times will give you the execution time.
Here’s an example:
@echo off
set start=%time%
my-command
set end=%time%
echo Execution Time: %start% - %end%
In PowerShell, you can achieve the same result using the Get-Date
cmdlet and calculating the time difference between the start and end times.
Here’s an example:
$startTime = Get-Date
my-command
$endTime = Get-Date
$executionTime = $endTime - $startTime
Write-Host "Execution Time: $executionTime"
These manual methods provide more flexibility and can be customized to suit your specific needs. 🛠️
Call-to-Action: Share Your Favorite Method! 📣
Now that you know multiple ways to measure the execution time of a command on the Windows command line, it’s your turn to share your favorite method! Have you used any of the options mentioned above? Or do you have an alternative approach?
Leave a comment below and let us know which method you prefer or if you have any additional tips to share. Let’s start a conversation and help each other make the most of our command line experience! 👇💬
Remember, knowing the execution time of your commands can be valuable in optimizing your workflow and improving overall efficiency. Happy measuring! ⏲️✨
In this article, Bardimin will share a script that you can use to calculate the time it takes for an application or command to complete .
The method is quite easy, copy the following script to notepad and save it with the name ” ExecutionTime.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 Execution time %hours%:%mins%:%secs%.%ms% (%totalsecs%.%ms%s total)
How to use
You can use the script from CMD with the command
ExecutionTime [your command]
For example, you want to calculate the execution time required by the file ” myscript.bat ” you can use the following command
ExecutionTime myscript.bat
And if you want to count the length of time you use Microsoft Word. You can type as follows
ExecutionTime "C:\Program Files ( x86)\ Microsoft Office\root\ Office16\WINWORD.EXE"
Home » PC Utilities » 8 Batch File Timers to Measure Execution Time of Windows Command Line
This guide will show you various tools to measure the execution time of batch scripts on your Windows PC. Whether you’re troubleshooting performance or optimizing processes, understanding script runtime is key.
We’ll walk you through several built-in Windows tools that allow you to track and analyze execution time. By the end, you’ll be equipped to use these tools to improve your system’s performance and automate time-sensitive tasks efficiently.
Ready to dive in? Let’s get started!
Best tools to measure execution time in Windows Command Line
1. ptime – Measure execution time in seconds with precision
ptime is a small and free tool that was released way back in 2002. It still works perfectly fine in Windows 10/11 and is a tool we’ve used before to time encodes with FFMpeg.
Using ptime to measure the time to finish executing a command is as easy as adding the command and optional arguments after the filename.
A slight drawback is ptime will only output seconds, so longer timed commands might be more difficult to read.
Once the task completes you will get a simple “Execution time: ***” at the end, shown in seconds. ptime claims that the measured execution time is accurate to 5 milliseconds or better although it says you shouldn’t take the thousandths digit too literally.
The supplied command can also be a batch file so you can get the overall execution time of an entire script, not just a single command.
Download ptime
2. TimeThis – Track time with verbose output for commands
TimeThis is an official Microsoft tool from the Windows 2000 Resource Kit. Even though TimeThis is positively ancient and dates back to 1999, it still works fine on the latest versions of Windows.
The TimeThis.exe executable file is installed in C:\Program Files (x86)\Resource Kit\ and the installer doesn’t set a path that allows it to run anywhere.
Copy the executable to Windows or System32 to avoid continually having to type the full path.
The usage of TimeThis is pretty straightforward and you just add an external command with optional arguments to the line.
The output is quite verbose with the command and start time listed first. Then the end time and elapsed time is also shown when the process has been completed.
Download TimeThis
3. Gammadyne Timer – Simple start/stop timer for command executions.
The way Gammadyne Timer works is slightly different from the first two tools mentioned above. As the name suggests, it functions as a timer and calling the program the first time will start the timer running.
Run the program again with the /s switch and the timer will stop. The result will be the elapsed time between the start and stop commands.
Timer
Run Commands
Timer /s
Above is a simple example of a batch file using Gammadyne Timer to measure the amount of time taken to run the executable. Any number of other utilities or tools can be executed in between the start and stop commands and it will simply give an overall time taken.
There are some useful command line switches for Gammadyne Timer. These include hiding the program banner, not reporting the start time, reporting elapsed time without stopping (split timer), or stopwatch mode (stop the timer on key press).
Gammadyne Timer could be used in a multitude of scenarios in Windows for almost anything that you want to measure a time for.
Download Gammadyne Timer
4. TimeMem – Advanced execution time with memory and IO stats
TimeMem is ported from the Unix time utility. Instead of just showing the total time of executing a command, it also provides other information pertaining to memory usage and IO statistics such as exit code, kernel time, user time, page fault, working set, paged pool, non-paged pool, and page file size.
TimeMem requires msvcr100.dll, a Microsoft Visual C++ 2010 Redistributable file in order to run. If you don’t have it installed already, a popup will appear saying “The program can’t start because MSVCR100.dll is missing from your computer. Try reinstalling the program to fix this problem”. If that’s the case, you can download msvcr100.dll from here and place it at the same location as TimeMem.
Download TimeMem
5. TimedExec – Benchmark command time across multiple runs
While the other tools listed here are used in a more simplistic capacity of measuring the time taken to run a command or script, TimedExec is a little bit different. Its main purpose is to be a benchmarking tool that measures the time it takes to execute a command over several runs, then gives the results.
By default, TimedExec will first run a warmup pass and then it will run the command five times to get a result. You will get various results displayed, such as mean time, median time, confidence intervals, deviation, and fastest/slowest times, but not overall time. If you wish to run the allowed minimum of three passes with no warmup, a few environment variables need to be changed first.
Set TIMED_EXEC_PASSES=3
Set TIMED_EXEC_WARMUP_PASSES=0
Enter those into Command Prompt or a batch script before running TimedExec. A log file is also created in the same folder as the TimedExec executable.
Note that TimedExec sets its path exclusively to its own folder so directly running commands like Ping or IPConfig will require the full path. Internal DOS commands like Dir, Echo, MkDir, or Copy won’t work at all when run directly as they have no path. The obvious solution would be to run commands from a batch file, then you only have to supply the full path to the script itself.
Download TimedExec
6. Command Prompt And Batch File – Built-in time tracking with Windows commands
There are various different ways to get an execution time for a command or script using nothing more than console commands built into Windows. Here are three different options.
Using Built In Variables
You can print the current time and date on the command line with the %TIME% and %DATE% variables. This simple method works in a similar way to Gammadyne Timer whereby you print the first time, run the command, then print the second time. The time taken to complete the operation is obviously the difference between the two.
ECHO Start Measure %Time% > timer.txt
Your Commands Here
ECHO Stop Measure %Time% >> timer.txt
This method crucially differs from Gammadyne Timer in one key area, which is the result between the two times. Here you have to work out the difference between the hours, minutes, and seconds yourself. It’s a basic rough and ready solution that probably works best with execution times of relatively short periods so it’s easier to work out the difference quickly.
Batch Script With Converted Duration Time
Another option along the same lines is a batch script that automatically converts the start and end times into a duration time. You add your own commands inside the script at the specified location and the conversion is done for you on completion.
The script still uses the before and after times of the %TIME% variable. Instead of just showing both times, it subtracts one from the other and gives the result in a readable format. Download the script with duration time, open it for editing, and enter your commands in the area indicated.
Call An External Script For Batch Files And Console Commands
As a final option, you can use a custom batch script as a command to run other scripts or single commands. It would work in a similar way to other tools above, such as ptime, while only using built in Windows commands and requires no external third party help. Use the script as follows:
TimerCmd.Bat Command {Arguments} or Script name
For the best results, it is recommended to copy the batch file to a Windows path location, such as C:\Windows or C:\Windows\System32. Then you can call TimerCmd.Bat from anywhere without having to supply a path every time. The %TIME% variable is again used to get before and after timings and the difference is calculated to get a readable result.
Download TimerCmd Batch File
7. Windows PowerShell
PowerShell is a more advanced command line shell that you can find built into Windows starting from Windows 7. Like with the Command Prompt option above, you don’t need use any third party tool to measure the time to execute a command. A cmdlet called Measure-Command can be used to measure the time it takes to run a command.
Measure-Command { Command }
Do take note that it is important to wrap the command that you want to measure with left and right curly brackets or else you’ll get an invalid argument error.
Measure-Command ( Command | Out-Default }
The first command above will actually run quietly with no output while the command is running and just display the timer result. The second command will also show the output of the command in the current console window, then show the timed result when it’s finished.
8. TimeIt
Although we found two tools with the same TimeIt name, we’ll focus on the one that has a couple of extra functions. The TimeIt version from jftuga is available on GitHub and is cross platform with versions for Linux and Mac OS as well as Windows.
TimeIt Command {Arguments}
What’s interesting about this tool is it can give you a simple execution time after running a command (like ptime) or run a start and stop timer with multiple commands or a btach file in between (like Gammadyne Timer).
TimeIt _Start
Run commands or a batch script
TimeIt _End
It’s probably total overkill for most users but TimeIt is able to show time results with up to seven decimal places. The second TimeIt we found is very similar to ptime and simply shows the result time at the end of the command.
Download TimeIt
Automating Tasks with Batch Commands
Writing batch commands is an excellent way to automate tasks in Windows without needing to know a full programming language. With dozens of built-in commands, you can perform various actions like pinging an IP address, retrieving directory information, copying files, adding or editing user accounts, managing hard disk issues, controlling network connections (wired or WiFi), killing tasks, and modifying the registry, among many others.
Getting Started with Batch Files
To create a batch file, simply launch Notepad and start typing your commands. Save the text file with a .bat
extension, and Windows will automatically recognize it as a batch file. When executed, the system will run the commands you’ve written. Occasionally, some commands may fail or not execute properly. A simple solution to this is to measure the time taken to run each command and set delays between them to ensure smooth execution.
Benchmarking with Batch Files
Measuring the execution time of a command can also serve benchmarking purposes. For example, you can track the time it takes to copy files between computers to test the efficiency of your system. Additionally, you can use tools for benchmarking hard drives, providing valuable insights into your computer’s performance.
By combining batch files with these techniques, you’ll be able to automate time-sensitive tasks and optimize your system’s performance.
Подсчитать время выполнения в cmd-скрипте можно разными способами. Один из них — спомощью утилиты из ресурскита timethis.exe
- Timethis (timethis.exe): Это средство командной строки
вычисляет, сколько занимает системы для выполнения команды. Чтобы
загрузить данное средство, щелкните следующую ссылку:
Ее удобно использовать чтобы узнать время выполнения какой-либо команды. Но если нужно узнать время выполнения всего скрипта, то стоит обратить внимание на такой интересный способ получения времени выполнения через WMIC:
Перед выполнением команды вызываем :SaveTime, а после — :DiffTime
Пример батника. Архивируем папку и смотрим сколько это заняло времени.
SET SourceDir = C:\temp
SET DestDir = D:\BackupCall :SaveTime
«C:\Program Files\7-Zip\7z» a -tzip %SourceDir%\SourceDir.zip %DestDir%\
Call :DiffTime
Echo Running time %DiffTime% sec
Echo.
Pause
Exit:SaveTime
For /F «Tokens=1 Delims=.» %%i In (‘WMIC OS Get LocalDateTime^|Find «.»‘) Do Set $Time=%%i
Set $D0=%$Time:~6,2%
Set $H0=%$Time:~8,2%
Set $N0=%$Time:~10,2%
Set $S0=%$Time:~12,2%
GoTo :EOF:DiffTime
For /F «Tokens=1 Delims=.» %%i In (‘WMIC OS Get LocalDateTime^|Find «.»‘) Do Set $Time=%%i
Set $D1=%$Time:~6,2%
Set $H1=%$Time:~8,2%
Set $N1=%$Time:~10,2%
Set $S1=%$Time:~12,2%Set DiffTime=-1
If %$D1% EQU %$D0% Set /A DiffTime=%$S1%+(%$N1%*60)+(%$H1%*3600)-(%$H0%*3600)-(%$N0%*60)-%$S0%
GoTo :EOF
Written : 2023-02-12 Last Update : 2023-02-12
Requirement
I wanted to see if there is an alternative to time
command on windows too, using which i can find execution time of a command. Did some search , found out a solution and in this Blog , I am mentioning it for future use or I hope it helps someone too.
Solution
PowerShell has a cmdlet for this called Measure-Command
. And since powershell is available on almost all newer windows (including and after win 7), we are safe to go with this.
Measure-Command captures the command’s output.So h1
won’t be displayed on your terminal. You can redirect the output back to your console using Out-Default.
This command returns a TimeSpan object, so the measured time is printed in such Detail . You can format the object into a timestamp string using ToString()
.
NOTE
: If the command inside Measure-Command changes your console text color, use[Console]::ResetColor()
to reset it back to normal.
So for instance, If you want to see how much time npx takes to create a react js project , you can use.
Or , if you want to know , How much time does your system takes to build a flutter apk, You can use.