There are times when you want to measure how long some piece of code takes to execute or compare it to another piece of code to decide if one is faster than the other. There are plenty of options for measuring how long a command takes to execute. Here I’ll show an example in PowerShell using the Measure-Command cmdlet.

1
2
$duration = Measure-Command -Expression { $result = Get-ChildItem -Path "$env:userprofile\Documents\*.pdf" -Recurse }
"Duration: $($duration.TotalMilliseconds) ms"

Alternatively, we could leverage the .NET stopwatch object.

1
2
3
4
$stopwatch = [System.Diagnostics.StopWatch]::StartNew()
$result = Get-ChildItem -Path "$env:userprofile\Documents\*.pdf" -Recurse
$stopwatch.Stop()
"Duration: $($stopwatch.ElapsedMilliseconds) ms"