Using a Stopwatch to Profile Scripts

by Sep 21, 2016

Ever wanted to find out how long a particular command or portion of your script took to complete? Here is a simple Stopwatch object that can help you do this:

# create a new stopwatch
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()

# run a command
$info = Get-Hotfix

# stop the stopwatch, and report the milliseconds
$stopwatch.Stop()
$stopwatch.Elapsed.Milliseconds

# continue the stopwatch
$stopwatch.Start()
# $stopwatch.Restart()  # <- resets stopwatch

# run another command
$files = Get-ChildItem -Path $env:windir

# again, stop the stopwatch and report accumulated runtime in milliseconds
$stopwatch.Stop()
$stopwatch.Elapsed.Milliseconds

The stopwatch works much better than working with Get-Date yourself, and calculating timespans. The stopwatch can be stopped, continued, and reset, and always automatically reports the elapsed time. You can, for example, stop the stopwatch while you do diagnostics, then restart it when the next command is ready to run.

In the example above, when you replace the second call to Start() by Restart(), the stopwatch is reset and would report the runtime for the second command instead of the overall elapsed time.

Twitter This Tip! ReTweet this Tip!