之前我正在阅读关于SO的一个很好的答案,我想知道为什么它还没有在PowerShell中被模仿.
在unix/linux中,我们可以使用该time命令作为简单的基准测试工具.
$ time ./script1.sh
real 0m1.005s
user 0m0.000s
sys 0m0.008s
Run Code Online (Sandbox Code Playgroud)
在powershell中,我们可以使用measure-command类似的:
$ Measure-Command {java post_incr}
Days : 0
Hours : 0
Minutes : 0
Seconds : 1
Milliseconds : 18
Ticks : 10188003
TotalDays : 1.17916701388889E-05
TotalHours : 0.000283000083333333
TotalMinutes : 0.016980005
TotalSeconds : 1.0188003
TotalMilliseconds : 1018.8003
Run Code Online (Sandbox Code Playgroud)
但这与time报告真实,用户和系统的报告不同(请参阅链接的SO答案中的三者之间的区别.)
这(time)显然是一个非常有用的小工具.是否有任何用户编写此功能的cmdlet,或者它已经在V3中或计划用于将来的版本?
System.Diagnostics.Process我使用了和提供的时间GetProcessTimes来提出以下实现time:
$source=@'
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
public class Timer
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern bool GetProcessTimes(IntPtr handle, out long creation, out long exit, out long kernel,
out long user);
public static void Time(string file,string args)
{
long user,kernel,exit,creation;
Process proc = null;
proc = Process.Start(file,args);
proc.WaitForExit();
GetProcessTimes(proc.Handle, out creation, out exit, out kernel, out user);
long real = exit - creation;
Console.WriteLine("real {0}\nuser {1}\nsys {2}", real / 10000000.0, user/10000000.0,kernel/10000000.0);
}
}
'@
Add-Type -TypeDefinition $source -Language CSharpVersion3
function time ($scriptblock) {
$file = "powershell";
$args = $scriptblock;
$startInfo = new-object Diagnostics.ProcessStartInfo;
$startInfo.FileName = $file;
$startInfo.Arguments = $args;
$startInfo.CreateNoWindow = $true;
$startInfo.UseShellExecute = $false;
$startInfo.RedirectStandardOutput = $true;
$process = [Diagnostics.Process]::Start($startInfo);
$process.WaitForExit();
write-host $process.StandardOutput.ReadToEnd();
write-host real: ($process.ExitTime - $process.StartTime)
write-host user: $process.UserProcessorTime;
write-host sys: $process.PrivilegedProcessorTime;
write-host using GetProcessTimes
[Timer]::Time($file,$args)
}
time {sleep 10}
Run Code Online (Sandbox Code Playgroud)
它并不完美,因为实时时间约为 11 秒( for sleep 10),因为我正在创建一个 powershell 进程并在其中运行命令。我将看看是否可以为此实现 cmdlet 或其他东西。
| 归档时间: |
|
| 查看次数: |
2447 次 |
| 最近记录: |