Often, I’ll see scripts that use Measure-Command
to calculate the length of time that code runs, while other code will use the $stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
method. I’d always thought that these were interchangable and practically identical, however, I’ve found out that they’re not. Depending on the code, there can be substantial time differences between the two.
Measure-Command
will discard the pipeline output, measuring only the time it takes to actually execute the command.
The stopwatch timer measures everything, including the time it takes to display any output to the console.
To have Measure-Command
to measure the time needed to write to the console, add an explicit pipe to Out-Host
inside the script block that you’re measuring. This will write the output to the console, and cause a corresponding increase in the measured time.