Skip to content

Instantly share code, notes, and snippets.

@Bigous
Created October 13, 2022 13:32
Show Gist options
  • Save Bigous/d5f44cadea03c4c79ed015b39211d812 to your computer and use it in GitHub Desktop.
Save Bigous/d5f44cadea03c4c79ed015b39211d812 to your computer and use it in GitHub Desktop.
PowerShell function to measure time execution of a program
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 %"
}
@Bigous
Copy link
Author

Bigous commented Oct 13, 2022

Usage

First install the global function on your shell:

./Measure-Time.ps1

Now you can use like this:

Measure-Time solve.exe

The output will be the output of the program and the statistics after the program ends:

   CROSS  :   96233
+  ROADS  :+  62513
 -------  : -------
  DANGER  :  158746


Kernel time : 00:00:00
User time   : 00:00:00.1406250
Elapsed     : 00:00:00.1546632
CPU         : 0.140625 %
Core cost   : 90.9233741445929 %

Using with a program that you must pass arguments is like this:

Measure-Time async-tests.exe -Arguments '100 10'

Output:

Starting thread: 1
Starting thread: 2
Starting thread: 3
Starting thread: 4
Starting thread: 5
Starting thread: 6
Starting thread: 7
Starting thread: 8
Starting thread: 9
Starting thread: 10
Result for thread 1: 4
Result for thread 2: 7
Result for thread 3: 4
Result for thread 4: 4
Result for thread 5: 6
Result for thread 6: 4
Result for thread 7: 11
Result for thread 8: 3
Result for thread 9: 6
Result for thread 10: 7
Ending...

Kernel time : 00:00:00.0156250
User time   : 00:00:48.6093750
Elapsed     : 00:00:07.9634306
CPU         : 48.625 %
Core cost   : 610.603676259827 %

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment