以下内容远非完美。但这是我能想到的最接近模拟 UNIX time 行为的方法。我相信它可以改进很多。
基本上,我正在创建一个 cmdlet,它接收脚本块、生成进程并使用 GetProcessTimes 获取内核、用户和已用时间。
加载 cmdlet 后,只需使用
调用它
Measure-Time -Command {your-command} [-silent]
-Silent 开关表示命令不生成任何输出(即您只对时间测量感兴趣)
例如:
Measure-Time -Command {Get-Process;sleep -Seconds 5} -Silent
生成的输出:
Kernel time : 0.6084039
User time : 0.6864044
Elapsed : 00:00:06.6144000
这里是 cmdlet:
Add-Type -TypeDefinition @"
using System;
using System.Runtime.InteropServices;
public class ProcessTime
{
[DllImport("kernel32.dll", CharSet = CharSet.Unicode)]
public static extern bool GetProcessTimes(IntPtr handle,
out IntPtr creation,
out IntPtr exit,
out IntPtr kernel,
out IntPtr user);
}
"@
function Measure-Time
{
[CmdletBinding()]
param ([scriptblock] $Command,
[switch] $Silent = $false
)
begin
{
$creation = 0
$exit = 0
$kernel = 0
$user = 0
$psi = new-object diagnostics.ProcessStartInfo
$psi.CreateNoWindow = $true
$psi.RedirectStandardOutput = $true
$psi.FileName = "powershell.exe"
$psi.Arguments = "-command $Command"
$psi.UseShellExecute = $false
}
process
{
$proc = [diagnostics.process]::start($psi)
$buffer = $proc.StandardOutput.ReadToEnd()
if (!$Silent)
{
Write-Output $buffer
}
$proc.WaitForExit()
}
end
{
$ret = [ProcessTime]::GetProcessTimes($proc.handle,
[ref]$creation,
[ref]$exit,
[ref]$kernel,
[ref]$user
)
$kernelTime = [long]$kernel/10000000.0
$userTime = [long]$user/10000000.0
$elapsed = [datetime]::FromFileTime($exit) - [datetime]::FromFileTime($creation)
Write-Output "Kernel time : $kernelTime"
Write-Output "User time : $userTime"
Write-Output "Elapsed : $elapsed"
}
}