Timing a command's execution in PowerShell

2019-01-07 02:46发布

Is there a simple way to time the execution of a command in PowerShell, like the 'time' command in Linux?
I came up with this:

$s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds

But I would like something simpler like

time .\do_something.ps1

7条回答
叼着烟拽天下
2楼-- · 2019-01-07 03:29

You can also get the last command from history and subtract its EndExecutionTime from its StartExecutionTime.

.\do_something.ps1  
$command = Get-History -Count 1  
$command.EndExecutionTime - $command.StartExecutionTime
查看更多
老娘就宠你
3楼-- · 2019-01-07 03:30

Using Stopwatch and formatting elapsed time:

Function FormatElapsedTime($ts) 
{
    $elapsedTime = ""

    if ( $ts.Minutes -gt 0 )
    {
        $elapsedTime = [string]::Format( "{0:00} min. {1:00}.{2:00} sec.", $ts.Minutes, $ts.Seconds, $ts.Milliseconds / 10 );
    }
    else
    {
        $elapsedTime = [string]::Format( "{0:00}.{1:00} sec.", $ts.Seconds, $ts.Milliseconds / 10 );
    }

    if ($ts.Hours -eq 0 -and $ts.Minutes -eq 0 -and $ts.Seconds -eq 0)
    {
        $elapsedTime = [string]::Format("{0:00} ms.", $ts.Milliseconds);
    }

    if ($ts.Milliseconds -eq 0)
    {
        $elapsedTime = [string]::Format("{0} ms", $ts.TotalMilliseconds);
    }

    return $elapsedTime
}

Function StepTimeBlock($step, $block) 
{
    Write-Host "`r`n*****"
    Write-Host $step
    Write-Host "`r`n*****"

    $sw = [Diagnostics.Stopwatch]::StartNew()
    &$block
    $sw.Stop()
    $time = $sw.Elapsed

    $formatTime = FormatElapsedTime $time
    Write-Host "`r`n`t=====> $step took $formatTime"
}

Usage Samples

StepTimeBlock ("Publish {0} Reports" -f $Script:ArrayReportsList.Count)  { 
    $Script:ArrayReportsList | % { Publish-Report $WebServiceSSRSRDL $_ $CarpetaReports $CarpetaDataSources $Script:datasourceReport };
}

StepTimeBlock ("My Process")  {  .\do_something.ps1 }
查看更多
我想做一个坏孩纸
4楼-- · 2019-01-07 03:35

Simples

function time($block) {
    $sw = [Diagnostics.Stopwatch]::StartNew()
    &$block
    $sw.Stop()
    $sw.Elapsed
}

then can use as

time { .\some_command }

You may want to tweak the output

查看更多
Bombasti
5楼-- · 2019-01-07 03:35

Measure-Command {echo "Good morning World!" | Write-Host}

Source - https://github.com/PowerShell/PowerShell/issues/2289#issuecomment-247793839

查看更多
Rolldiameter
6楼-- · 2019-01-07 03:44

Use Measure-Command

Example

Measure-Command { <your command here> | Out-Host }

The pipe to Out-Host allows you to see the output of the command, which is otherwise consumed by Measure-Command.

查看更多
虎瘦雄心在
7楼-- · 2019-01-07 03:51

Yup.

Measure-Command { .\do_something.ps1 }

Note that one minor downside of Measure-Command is that you see no stdout output. If you want to see the output, then you can use the .NET Stopwatch object e.g.:

$sw = [Diagnostics.Stopwatch]::StartNew()
.\do_something.ps1
$sw.Stop()
$sw.Elapsed
查看更多
登录 后发表回答