Linux の「time」コマンドのように、PowerShell でコマンドの実行時間を計測する簡単な方法はありますか?
私はこれを思いついた:
$s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds
しかし、私は次のようなより単純なものが欲しい
time .\do_something.ps1
Linux の「time」コマンドのように、PowerShell でコマンドの実行時間を計測する簡単な方法はありますか?
私はこれを思いついた:
$s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds
しかし、私は次のようなより単純なものが欲しい
time .\do_something.ps1
うん。
Measure-Command { .\do_something.ps1 }
のマイナーな欠点の 1 つは、出力 Measure-Command
が表示されないことです。stdout
[更新、@JasonMArcher に感謝] コマンド出力を、ホストに書き込むコマンドレットにパイプすることで修正できます。たとえば、次のOut-Default
ようになります。
Measure-Command { .\do_something.ps1 | Out-Default }
出力を表示する別の方法は、次のように .NETStopwatch
クラスを使用することです。
$sw = [Diagnostics.Stopwatch]::StartNew()
.\do_something.ps1
$sw.Stop()
$sw.Elapsed
EndExecutionTime
履歴から最後のコマンドを取得し、そのからそれを減算することもできますStartExecutionTime
。
.\do_something.ps1
$command = Get-History -Count 1
$command.EndExecutionTime - $command.StartExecutionTime
シンプル
function time($block) {
$sw = [Diagnostics.Stopwatch]::StartNew()
&$block
$sw.Stop()
$sw.Elapsed
}
その後、次のように使用できます
time { .\some_command }
出力を微調整したい場合があります
time
以下は、Unixコマンドと同様に機能する、私が作成した関数です。
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
}
}
ソース: https://gist.github.com/bender-the-greatest/741f696d965ed9728dc6287bdd336874
ストップウォッチの使用と経過時間の書式設定:
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"
}
使用例
StepTimeBlock ("Publish {0} Reports" -f $Script:ArrayReportsList.Count) {
$Script:ArrayReportsList | % { Publish-Report $WebServiceSSRSRDL $_ $CarpetaReports $CarpetaDataSources $Script:datasourceReport };
}
StepTimeBlock ("My Process") { .\do_something.ps1 }