在PowerShell中是否有一种简单的方法来计时命令的执行,就像Linux中的'time'命令一样? 我想到了这个:
$s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds
但我想要简单点的,比如
time .\do_something.ps1
在PowerShell中是否有一种简单的方法来计时命令的执行,就像Linux中的'time'命令一样? 我想到了这个:
$s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds
但我想要简单点的,比如
time .\do_something.ps1
当前回答
Yup.
Measure-Command { .\do_something.ps1 }
注意,Measure-Command的一个小缺点是看不到标准输出。
[更新,感谢@JasonMArcher]你可以通过将命令输出输出到一些可写入主机的命令集来修复这个问题,例如Out-Default,这样它就变成:
Measure-Command { .\do_something.ps1 | Out-Default }
查看输出的另一种方法是使用。net Stopwatch类,像这样:
$sw = [Diagnostics.Stopwatch]::StartNew()
.\do_something.ps1
$sw.Stop()
$sw.Elapsed
其他回答
简单的
function time($block) {
$sw = [Diagnostics.Stopwatch]::StartNew()
&$block
$sw.Stop()
$sw.Elapsed
}
然后可以用as
time { .\some_command }
您可能需要调整输出
您还可以从历史记录中获取最后一个命令,并从它的StartExecutionTime中减去它的EndExecutionTime。
.\do_something.ps1
$command = Get-History -Count 1
$command.EndExecutionTime - $command.StartExecutionTime
Yup.
Measure-Command { .\do_something.ps1 }
注意,Measure-Command的一个小缺点是看不到标准输出。
[更新,感谢@JasonMArcher]你可以通过将命令输出输出到一些可写入主机的命令集来修复这个问题,例如Out-Default,这样它就变成:
Measure-Command { .\do_something.ps1 | Out-Default }
查看输出的另一种方法是使用。net Stopwatch类,像这样:
$sw = [Diagnostics.Stopwatch]::StartNew()
.\do_something.ps1
$sw.Stop()
$sw.Elapsed
一种更受PowerShell启发的方式来访问您关心的属性值:
$myCommand = .\do_something.ps1
Measure-Command { Invoke-Expression $myCommand } | Select -ExpandProperty Milliseconds
4
As Measure-Command返回一个TimeSpan对象。
注意:TimeSpan对象也有TotalMilliseconds作为双变量(如上面我的例子中的4.7322 TotalMilliseconds),这可能对您有用。就像TotalSeconds, TotalDays等。
使用Measure-Command
例子
Measure-Command { <your command here> | Out-Host }
到Out-Host的管道允许您查看命令的输出,即 否则由测量命令消耗。