2013-11-14 46 views
3

请详细告诉我时间命令的执行流程。PowerShell中相当于时间的命令

我在PowerShell中有一个用户创建的函数,它将按以下方式计算执行命令的时间。 1.它将打开新的PowerShell窗口。 2.它将执行该命令。 4.它将关闭PowerShell窗口。 3.它将使用GetProcessTimes函数获得不同的执行时间。 URL ref:http://msdn.microsoft.com/en-us/library/windows/desktop/ms683223(v=vs.85).aspx

我想知道unix中的“时间命令”是否也以相同的方式计算。

非常感谢。

回答

9

Measure-Command cmdlet是你的朋友。

PS> Measure-Command -Expression {dir} 

您也可以从命令历史记录的执行时间(最后在这个例子中执行的命令):

$h = Get-History -Count 1 
$h.EndExecutionTime - $h.StartExecutionTime 
+1

仍然获得stdout使用'| | Out-Default'如此'Measure-Command -Expression {dir | Out-Default}' – KCD

1

如果你需要衡量的财产以后所花费的时间,你可以按照这个blog entry

基本上,它建议使用.NET StopWatch class

$sw = [system.diagnostics.stopwatch]::startNew() 

# the code you measure 

$sw.Stop() 
Write-Host $sw.Elapsed 
+0

我不得不承认@shayLevy的回答远比我的好。 –

2

我一直在做这样的:

Time {npm --version ; node --version} 

有了这个功能,你可以把你的$profile文件:

function Time([scriptblock]$scriptblock, $name) 
{ 
<# 
.SYNOPSIS 
Run the given scriptblock, and say how long it took at the end. 
.DESCRIPTION 
.PARAMETER scriptBlock 
a single computer name or an array of computer names. You mayalso provide IP addresses. 
.PARAMETER name 
Use this for long scriptBlocks to avoid quoting the entire script block in the final output line 
.EXAMPLE 
    time { ls -recurse} 
.EXAMPLE 
    time { ls -recurse} "All the things" 
#> 
    if (!$stopWatch) 
    { 
     $script:stopWatch = new-object System.Diagnostics.StopWatch 
    } 
    $stopWatch.Reset() 
    $stopWatch.Start() 
    . $scriptblock 
    $stopWatch.Stop() 
    if ($name -eq $null) { $name = "$scriptblock" } 
    "Execution time: $($stopWatch.ElapsedMilliseconds) mS for $name" 
} 

Measure-Command工程,但它吞咽的标准输出正在运行的命令。 (另请参阅Timing a command's execution in PowerShell