Using a StopWatch to Measure Execution Times

by Dec 16, 2019

There are situations when you’d like to know how long some code took to execute, for example to return statistics or compare code, and there are plenty of ways to measure commands, including the Measure-Command cmdlet:

$duration = Measure-Command -Expression {
  $result = Get-Hotfix

$time = $duration.TotalMilliseconds

'{0} results in {1:n1} milliseconds' -f $result.Count, $time

Measure-Command has some unwelcomed side-effects, though:

  • All output is discarded so outputting data won’t influence the measured time, and you can’t control this behavior
  • It will slow down your code for a number of reasons, one of which is that Measure-Command executes the expression dot-sourced in a separate script block

Therefore, another technique is often employed and uses Get-Date like this:

$start = Get-Date
$result = Get-Hotfix
$end = Get-Date
$time = ($end - $start).TotalMilliseconds

'{0} results in {1:n1} milliseconds' -f $result.Count, $time

It works but also has unwelcomed side-effects:

  • It produces more code
  • When the computer is put into standby or hibernation, this affects the results because the end date does not take into account times where the computer was turned off

A much more elegant solution is to use the .NET stopwatch object which produces shorter code, does not slow down your code, and is immune against standby or hibernation:

$stopwatch =  [system.diagnostics.stopwatch]::StartNew()
$result = Get-Hotfix
$time = $stopwatch.ElapsedMilliseconds

'{0} results in {1:n1} milliseconds' -f $result.Count, $time

In addition, you can Stop(), Restart(), and Reset() your stopwatch. That way, you can pause measurements for some parts of your code (like data output) and then continue measuring.

You are a PowerShell Professional, passionate about improving your code and skills? You take security seriously and are always looking for the latest advice and guidance to make your code more secure and faster? You’d love to connect to the vibrant PowerShell community and get in touch with other PowerShell Professionals to share tricks and experience? Then PowerShell Conference EU 2020 might be just the right place for you: (June 2-5, 2020 in Hanover, Germany).

It’s a unique mixture of classic conference with three parallel tracks filled with fast-paced PowerShell presentations, and advanced learning class with live discussions, Q&A and plenty of networking.

Secure your seat while they last: Help build the agenda and make this “your” event by submitting hypothetical sessions you’d like to hear: And if you’d like to present yourself and join the speakers’ team, submit proposals:

Twitter This Tip! ReTweet this Tip!