Measure-Command

Measure the running time of a script block or cmdlet.

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).

       When the -InputObject parameter is used to submit a collection of items,
       Measure-Command receives one object that represents the collection.
       Because one collection object cannot be measured, Measure-Command returns the entire collection unchanged.

       To measure multiple items, pipe them to Measure-Command.

       This parameter is an implementation detail: its purpose is to enable input via the pipeline, and its
       direct use with arrays (collections) does not (yet) provide any useful functionality.

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.
Measure-Script - (PSProfiler module) Runtime profiling tool for PowerShell 5+.
Equivalent CMD script: timer.cmd
Equivalent bash command: time - Measure program running time.


 
Copyright © 1999-2024 SS64.com
Some rights reserved