Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Timing a command's execution in PowerShell

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 
like image 370
Paolo Tedesco Avatar asked Aug 18 '10 15:08

Paolo Tedesco


People also ask

How do I delay a PowerShell script execution?

In PowerShell, we can use the Start-Sleep cmdlet to suspend/pause/sleep/wait the activity in a script or session for the specified period of time. You can use it for many tasks, such as waiting for an operation to be completed or pausing before repeating an operation.

How do you wait 5 seconds in PowerShell?

Using the PowerShell Start Sleep cmdlet You can also write Start-Sleep 5 to let the script sleep for 5 seconds.

How do you wait for a process to finish in PowerShell?

The Wait-Process cmdlet waits for one or more running processes to be stopped before accepting input. In the PowerShell console, this cmdlet suppresses the command prompt until the processes are stopped. You can specify a process by process name or process ID (PID), or pipe a process object to Wait-Process .


2 Answers

Yup.

Measure-Command { .\do_something.ps1 } 

Note that one minor downside of Measure-Command is that you see no stdout output.

[Update, thanks to @JasonMArcher] You can fix that by piping the command output to some commandlet that writes to the host, e.g. Out-Default so it becomes:

Measure-Command { .\do_something.ps1 | Out-Default } 

Another way to see the output would be to use the .NET Stopwatch class like this:

$sw = [Diagnostics.Stopwatch]::StartNew() .\do_something.ps1 $sw.Stop() $sw.Elapsed 
like image 119
Keith Hill Avatar answered Sep 22 '22 05:09

Keith Hill


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

.\do_something.ps1   $command = Get-History -Count 1   $command.EndExecutionTime - $command.StartExecutionTime 
like image 25
Shay Levy Avatar answered Sep 23 '22 05:09

Shay Levy