18

What is the flow of execution of the time command in detail?

I have a user created function in PowerShell, which will compute the time for execution of the command in the following way.

  1. It will open the new PowerShell window.
  2. It will execute the command.
  3. It will close the PowerShell window.
  4. It will get the the different execution times using the GetProcessTimes function function.

Is the "time command" in Unix also calculated in the same way?

0

3 Answers 3

29

The Measure-Command cmdlet is your friend.

PS> Measure-Command -Expression {dir}

You could also get execution time from the command history (last executed command in this example):

$h = Get-History -Count 1
$h.EndExecutionTime - $h.StartExecutionTime
Sign up to request clarification or add additional context in comments.

3 Comments

To still get the stdout use | Out-Default so Measure-Command -Expression {dir | Out-Default}
Is it only my impression or is PowerShell extremely wordy?
Get-History just made my day! I never knew! Maybe a bit wordy, but powerful as well!
11

I've been doing this:

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

With this function, which you can put in your $profile file:

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 works, but it swallows the stdout of the command being run. (Also see Timing a command's execution in PowerShell)

Comments

1

If you need to measure the time taken by something, you can follow this blog entry.

Basically, it suggest to use the .NET StopWatch class:

$sw = [System.Diagnostics.StopWatch]::startNew()

# The code you measure

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

1 Comment

I have to admit that @shayLevy 's answer is far better than mine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.