加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Windows > 正文

Windows命令行相当于Linux中的“时间”?

发布时间:2020-12-14 01:44:09 所属栏目:Windows 来源:网络整理
导读:参见英文答案 How do I measure execution time of a command on the Windows command line?29个 Equivalent of Unix time command in PowerShell?4个 我有一个可能是一个愚蠢的问题,但我似乎无法在网上找到答案.在基于linux的系统中,在终端中输入“time”之
参见英文答案 > How do I measure execution time of a command on the Windows command line?29个
> Equivalent of Unix time command in PowerShell?4个
我有一个可能是一个愚蠢的问题,但我似乎无法在网上找到答案.在基于linux的系统中,在终端中输入“time”之前,任何命令都会根据实际,用户和系统时间给出命令所需的时间.例如,输入
time ls

列出当前目录中的文件和文件夹,然后列出列出文件和文件夹所花费的实际,用户和系统时间.有窗户相当吗?我试图比较不同算法的性能,但没有Linux机器工作,所以我希望在Windows中有类似的命令.

以下内容远非完美.但它是我能够最接近模拟UNIX时间行为的.我相信它可以改进很多.

基本上我正在创建一个接收脚本块的cmdlet,生成一个进程并使用GetProcessTimes来获取Kernel,User和Elapsed次.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读