Timing a command's execution in PowerShell

前端 未结 7 806
没有蜡笔的小新
没有蜡笔的小新 2020-11-28 01:13

Is there a simple way to time the execution of a command in PowerShell, like the \'time\' command in Linux?
I came up with this:

$s=Get-Date; .\\do_somet         


        
相关标签:
7条回答
  • 2020-11-28 02:04

    Using Stopwatch and formatting elapsed time:

    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"
    }
    

    Usage Samples

    StepTimeBlock ("Publish {0} Reports" -f $Script:ArrayReportsList.Count)  { 
        $Script:ArrayReportsList | % { Publish-Report $WebServiceSSRSRDL $_ $CarpetaReports $CarpetaDataSources $Script:datasourceReport };
    }
    
    StepTimeBlock ("My Process")  {  .\do_something.ps1 }
    
    0 讨论(0)
提交回复
热议问题