Pao*_*sco 198 powershell time
有没有一种简单的方法来计算PowerShell中命令的执行时间,比如Linux中的'time'命令?
我想出了这个:
$s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds
Run Code Online (Sandbox Code Playgroud)
但我想要更简单的东西
time .\do_something.ps1
Run Code Online (Sandbox Code Playgroud)
Kei*_*ill 309
对.
Measure-Command { .\do_something.ps1 }
Run Code Online (Sandbox Code Playgroud)
请注意,Measure-Command的一个小缺点是您没有看到stdout输出.如果要查看输出,则可以使用.NET Stopwatch对象,例如:
$sw = [Diagnostics.Stopwatch]::StartNew()
.\do_something.ps1
$sw.Stop()
$sw.Elapsed
Run Code Online (Sandbox Code Playgroud)
Sha*_*evy 172
您还可以从历史记录中获取最后一个命令并从中减去EndExecutionTime
它StartExecutionTime
.
.\do_something.ps1
$command = Get-History -Count 1
$command.EndExecutionTime - $command.StartExecutionTime
Run Code Online (Sandbox Code Playgroud)
Dro*_*roj 99
使用 Measure-Command
例
Measure-Command { <your command here> | Out-Host }
Run Code Online (Sandbox Code Playgroud)
管道Out-Host
允许您查看命令的输出,否则将被消耗Measure-Command
.
小智 17
Simples
function time($block) {
$sw = [Diagnostics.Stopwatch]::StartNew()
&$block
$sw.Stop()
$sw.Elapsed
}
Run Code Online (Sandbox Code Playgroud)
然后可以用作
time { .\some_command }
Run Code Online (Sandbox Code Playgroud)
您可能想要调整输出
这是我编写的一个与 Unixtime
命令类似的函数:
function time {
Param(
[Parameter(Mandatory=$true)]
[string]$command,
[switch]$quiet = $false
)
$start = Get-Date
try {
if ( -not $quiet ) {
iex $command | Write-Host
} else {
iex $command > $null
}
} finally {
$(Get-Date) - $start
}
}
Run Code Online (Sandbox Code Playgroud)
来源:https : //gist.github.com/bender-the-greatest/741f696d965ed9728dc6287bdd336874
小智 7
一种更受 PowerShell 启发的方式来访问您关心的属性的价值:
$myCommand = .\do_something.ps1
Measure-Command { Invoke-Expression $myCommand } | Select -ExpandProperty Milliseconds
Run Code Online (Sandbox Code Playgroud)
4
Run Code Online (Sandbox Code Playgroud)
由于Measure-Command返回一个TimeSpan对象。
注意:TimeSpan 对象还具有双精度型 TotalMilliseconds(例如上面我的例子中的 4.7322 TotalMilliseconds),这可能对您有用。就像 TotalSeconds、TotalDays 等。
到目前为止,所有答案都达不到提问者(和我)通过简单地在命令行开头添加“time”来计时命令的愿望。相反,它们都需要将命令括在方括号 ( {}
) 中以形成一个块。下面是一个简短的函数,它的工作方式更像是time
在 Unix 上:
Function time() {
$command = $args -join ' '
Measure-Command { Invoke-Expression $command | Out-Default }
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
124799 次 |
最近记录: |