在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
当前回答
您还可以从历史记录中获取最后一个命令,并从它的StartExecutionTime中减去它的EndExecutionTime。
.\do_something.ps1
$command = Get-History -Count 1
$command.EndExecutionTime - $command.StartExecutionTime
其他回答
使用Measure-Command
例子
Measure-Command { <your command here> | Out-Host }
到Out-Host的管道允许您查看命令的输出,即 否则由测量命令消耗。
(measure-commmand{your command}).totalseconds
例如
(measure-commmand{.\do_something.ps1}).totalseconds
到目前为止,所有的答案都没有达到提问者(和我)想要通过在命令行开头添加“time”来计时的愿望。相反,它们都需要将命令包装在括号({})中以构成一个块。下面是一个简短的函数,在Unix上更像时间:
Function time() {
$command = $args -join ' '
Measure-Command { Invoke-Expression $command | Out-Default }
}
一种更受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等。
您还可以从历史记录中获取最后一个命令,并从它的StartExecutionTime中减去它的EndExecutionTime。
.\do_something.ps1
$command = Get-History -Count 1
$command.EndExecutionTime - $command.StartExecutionTime