PowerShell에서 명령 실행 타이밍 설정
Linux의 'time' 명령과 같이 PowerShell의 명령 실행 시간을 측정하는 간단한 방법이 있습니까?
내가 생각해낸 건 이거야
$s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds
하지만 나는 다음과 같은 간단한 것을 원한다.
time .\do_something.ps1
네.
Measure-Command { .\do_something.ps1 }
의 작은 단점 중 하나라는 것입니다.Measure-Command
안 보인다는 거야stdout
산출량.
[업데이트, @Jason 덕분]Marcher] 명령어 출력을 호스트에 쓰는 명령어에 파이핑하여 수정할 수 있습니다.Out-Default
그 결과, 다음과 같이 됩니다.
Measure-Command { .\do_something.ps1 | Out-Default }
출력을 표시하는 또 다른 방법은 를 사용하는 것입니다.그물Stopwatch
다음과 같은 클래스:
$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
사용하다Measure-Command
예
Measure-Command { <your command here> | Out-Host }
파이프가 에 연결되어 있다.Out-Host
명령어의 출력을 표시할 수 있습니다.이 출력은 에 의해 소비됩니다.Measure-Command
.
시뮬레이션
function time($block) {
$sw = [Diagnostics.Stopwatch]::StartNew()
&$block
$sw.Stop()
$sw.Elapsed
}
그럼 으로 사용할 수 있습니다.
time { .\some_command }
출력을 조정할 수 있습니다.
여기 UNIX와 비슷하게 작동하는 함수가 있습니다.time
명령어:
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
PowerShell에서 영감을 받아 관심 있는 자산의 가치에 액세스할 수 있는 방법:
$myCommand = .\do_something.ps1
Measure-Command { Invoke-Expression $myCommand } | Select -ExpandProperty Milliseconds
4
주의: TimeSpan 오브젝트에는 TotalMilliseconds가 2배(위의 경우 4.7322 TotalMilliseconds 등)로 설정되어 있어 편리합니다.TotalSeconds, TotalDays 등과 같이.
Stopwatch를 사용하여 경과 시간을 포맷합니다.
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 }
지금까지의 답변은 모두 명령줄 시작 부분에 "시간"을 추가하는 것만으로 명령 시간을 측정하려는 질문자의 희망에 미치지 못합니다.대신 모두 명령어를 괄호로 묶어야 합니다( ).{}
)를 사용하여 블록을 만듭니다.여기 더 잘 작동하는 짧은 기능이 있습니다.time
UNIX의 경우:
Function time() {
$command = $args -join ' '
Measure-Command { Invoke-Expression $command | Out-Default }
}
(measure-commmand{your command}).totalseconds
예를 들어.
(measure-commmand{.\do_something.ps1}).totalseconds
답변에서 언급된 성능 측정 명령에서 도출(잘못된) 결론에 대한 한마디입니다.(커스텀) 함수 또는 명령어의 최소 호출 시간을 조사하는 것 외에 고려해야 할 함정이 몇 가지 있습니다.
Sjoemel 소프트웨어
'Sjoemel software'가 2015년 올해의 네덜란드어로 선정
Sjoemelen은 부정행위를 의미하며, Sjoemelsoftware라는 단어는 폭스바겐의 배기 가스 배출 스캔들 때문에 생겨났다.공식 정의는 "시험 결과에 영향을 미치는 데 사용되는 소프트웨어"입니다.
개인적으로 "Sjoemel software"는 항상 테스트 결과를 속이기 위해 의도적으로 만들어진 것이 아니라 다음과 같은 테스트 사례와 유사한 실제 상황에 적응하는 데서 비롯되었다고 생각합니다.
예를 들어 나열된 성능 측정 명령어인 Language Integrated Query(LINQ)(1)를 사용하면 빠른 방법으로 작업을 수행할 수 있으며 대부분의 경우 하지만 항상 그렇지는 않습니다.기본 PowerShell 명령과 비교하여 계수 40 이상의 속도 증가를 측정하는 사용자는 잘못된 측정 또는 잘못된 결론을 도출하고 있을 수 있습니다.
요점은 어떤 것이라는 것이다.느린 평가(지연(2) 실행이라고도 함)를 사용하는 넷클래스(LINQ 등).즉, 변수에 식을 할당하면 거의 즉시 완료된 것처럼 보이지만 실제로는 아무것도 처리하지 않았습니다.
예를 들어, 데이터 소스의. .\Dosomething.ps1
또는 Linq 하기 표현은 )Measure-Command
$Data = @(1..100000).ForEach{[PSCustomObject]@{Index=$_;Property=(Get-Random)}}
(Measure-Command {
$PowerShell = $Data.Where{$_.Index -eq 12345}
}).totalmilliseconds
864.5237
(Measure-Command {
$Linq = [Linq.Enumerable]::Where($Data, [Func[object,bool]] { param($Item); Return $Item.Index -eq 12345})
}).totalmilliseconds
24.5949
결과는 명백합니다. 최신 Linq 명령은 첫 번째 PowerShell 명령보다 약 40배 빠릅니다.불행히도, 그렇게 간단하지 않아요...
결과를 표시합니다.
PS C:\> $PowerShell
Index Property
----- --------
12345 104123841
PS C:\> $Linq
Index Property
----- --------
12345 104123841
결과는 하지만 주의, 보다 이 걸렸다는 을 알 수 입니다.$Linq
후, 「」의 결과가 됩니다.$PowerShell
★★★★★★ 。
결과 객체의 속성을 검색하는 것만으로 구체적으로 측정해 보겠습니다.
PS C:\> (Measure-Command {$PowerShell.Property}).totalmilliseconds
14.8798
PS C:\> (Measure-Command {$Linq.Property}).totalmilliseconds
1360.9435
의 속성을 회복하는 데 약 90배 더 오래 걸렸습니다.$Linq
$PowerShell
!!고!!!!!!!!
또 다른 함정에 주의해 주십시오.그것은 일부 표현이 캐시되어 있기 때문입니다.
결론적으로 두 기능 간의 성능을 비교하려면 사용 중인 경우에 구현하고 새로운 PowerShell 세션부터 시작하여 전체 솔루션의 실제 성능을 기반으로 결론을 내려야 합니다.
(1) PowerShell 및 LINQ에 대한 자세한 배경과 예는 다음 사이트를 참조하십시오.LINQ를 탑재한 고성능 PowerShell
(2) 두 개념 사이에는 약간의 차이가 있다고 생각합니다.지속적인 평가에서는 시스템이 아이돌 상태일 때 결과를 계산했을 때 실행이 지연되었을 때 필요에 따라 결과를 계산하기 때문입니다.
언급URL : https://stackoverflow.com/questions/3513650/timing-a-commands-execution-in-powershell
'itsource' 카테고리의 다른 글
git 풀 실행 취소, 저장소를 이전 상태로 되돌리는 방법 (0) | 2023.04.17 |
---|---|
Swift의 Documents 디렉토리에 파일이 있는지 확인하는 방법 (0) | 2023.04.17 |
명령줄 인수를 Bash에서 배열로 변환 (0) | 2023.04.17 |
상각된 상수 시간 동안 R의 목록에 개체를 추가하시겠습니까, O(1)? (0) | 2023.04.17 |
Bash 이력에 명령어가 표시되지 않도록 하려면 어떻게 해야 합니까? (0) | 2023.04.17 |