Created
October 13, 2022 13:32
-
-
Save Bigous/d5f44cadea03c4c79ed015b39211d812 to your computer and use it in GitHub Desktop.
PowerShell function to measure time execution of a program
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function global:Measure-Time | |
{ | |
[CmdletBinding()] | |
param ([string] $Command, | |
[string] $Arguments = "", | |
[switch] $Silent = $false | |
) | |
$creation = 0 | |
$exit = 0 | |
$kernel = 0 | |
$user = 0 | |
$fileName="$(pwd)\$Command" | |
if(!(Test-Path $fileName)) { | |
$fileName = $Command | |
if(!(Test-Path $fileName)) { | |
Write-Error "$Command not found" | |
return | |
} | |
} | |
$psi = new-object diagnostics.ProcessStartInfo | |
$psi.CreateNoWindow = $true | |
$psi.RedirectStandardOutput = $true | |
$psi.WorkingDirectory = (pwd) | |
$psi.FileName = "$fileName" | |
$psi.Arguments = "$Arguments" | |
$psi.UseShellExecute = $false | |
$proc = [diagnostics.process]::start($psi) | |
$proc.WaitForExit() | |
$buffer = $proc.StandardOutput.ReadToEnd() | |
if (!$Silent) | |
{ | |
Write-Output $buffer | |
} | |
$kernelTime = $proc.PrivilegedProcessorTime | |
$userTime = $proc.UserProcessorTime | |
$elapsed = $proc.ExitTime - $proc.StartTime | |
$CPU = $proc.CPU | |
$CoreCost = (($userTime + $kernelTime) / $elapsed) * 100.0 | |
Write-Output "Kernel time : $kernelTime" | |
Write-Output "User time : $userTime" | |
Write-Output "Elapsed : $elapsed" | |
Write-Output "CPU : $CPU %" | |
Write-Output "Core cost : $CoreCost %" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage
First install the global function on your shell:
Now you can use like this:
The output will be the output of the program and the statistics after the program ends:
Using with a program that you must pass arguments is like this:
Output: