views:

56

answers:

2

Is there a simple way to time the execution of a command in PowerShell, like the 'time' command in Linux?
I came up with this:

$s=Get-Date; .\do_something.ps1 ; $e=Get-Date; ($e - $s).TotalSeconds

But I would like something simpler like

time .\do_something.ps1
+7  A: 

Yup.

Measure-Command { .\do_something.ps1 }

Note that one minor downside of Measure-Command is that you see no stdout output. If you want to see the output, then you can use the .NET Stopwatch object e.g.:

$sw = [Diagnostics.Stopwatch]::StartNew()
.\do_something.ps1
$sw.Stop()
$sw.Elapsed
Keith Hill
Perfect, thanks!
Paolo Tedesco
Very nice answer - can't wait to use it. I'd previously used the approach in the question, which isn't ideal.
cristobalito
You can also see output like this, Measure-Command {ps | Out-Default}. Or anything else that writes directly to the host, which may or may not be useful.
JasonMArcher
+5  A: 

You can also get the last command from history and subtract its EndExecutionTime from its StartExecutionTime.

.\do_something.ps1
$command = Get-History | Select-Object -Last 1
$command = Get-History -Count 1
$command.EndExecutionTime - $command.StartExecutionTime

Shay Levy
Wow, quite surprising. I have never heard about it :)
stej
Try this sometime: `Get-History | Group {$_.StartExecutionTime.Hour} | sort Count -desc` to see your PowerShell usage pattern by hour of day. :-)
Keith Hill
Cool... +1 from me :)
Paolo Tedesco