Measure-Command

Measure running time (for script blocks and cmdlets).

Syntax
      Measure-Command [-expression] scriptblock 
         [-inputObject psobject] [CommonParameters]
Key
   -expression 
       The expression to be timed.
       Enclose the expression in {curly braces}

   -inputObject
       An object that represents an expression.
       A command, expression or variable that contains the object(s).

Output text is Discarded

Measure-Command executes the expression dot-sourced in a separate script block, it also discards all output data. Writing output to the screen can slow down the script, so this provides more consistent measurements for A-B comparisons.

.NET stopwatch

The .Net stopwatch is an alternative method for measuring execution time for a block of code.

$stopwatch = [system.diagnostics.stopwatch]::StartNew()
$result = get-eventlog "windows powershell" # replace this with any command or scriptblock.
$stopwatch.Stop()
$time = $stopwatch.ElapsedMilliseconds
"Time Elapsed:  $time"
"Number of results: $result.Count"

The .Net stopwatch supports the methods: Stop(), Restart(), and Reset() so you can stop a measurement, output some text to show progress and then restart the measurement.

All of the measurement methods on this page will give inaccurate numbers if the computer goes into standby or hibernation during the test.

Examples

Measures the time it takes to run a "get-eventlog" command:

PS C:\> Measure-Command { get-eventlog "windows powershell" }

Compare the performance of -filter and -include:

PS C:\> measure-command {get-childitem c:\windows -include *.txt -recurse}
PS C:\> measure-command {get-childitem c:\windows -filter "*.txt" -recurse}

“There is no monument dedicated to the memory of a committee” ~ Lester J. Pourciau

Related PowerShell Cmdlets:

Compare-Object - Compare the properties of objects.
Trace-Command - Trace an expression or command.
Invoke-Expression - Run a PowerShell expression.
Equivalent CMD script: timer.cmd
Equivalent bash command: time - Measure program running time.


 
Copyright © 1999-2020 SS64.com
Some rights reserved