Timing command execution and memory usage...

I’m very new to powershell. I’ve been tasked with charting the runtime behaviors of several custom command line utilities.

In order to do this, I need to run the command X amount of times, and then average the runtimes together.

I also need to measure the maximum amount of memory that each command run uses and also average those together.

Is this possible with powershell? And if so can anyone give me some guidance?

I’ve looked at some commands, and figured Measure-Command {} might be the correct command to use to time the execution, but I’m not sure how to grab the ms number that results, nor how to average that though looping.

I have no idea where to even start on capturing memory usage.

You can use Measure-Command to run a command, and then obviously collect the results and do whatever analysis you want with them. However, there’s not a direct way of measuring memory of a single command. You could certainly look at the PowerShell process and measure it, but because of the way .NET works, it isn’t going to be terribly accurate. .NET won’t necessarily release memory until it’s made to do so by the OS, so it’s difficult to get a clear reading. The best would be to launch your command in a new process, measure its memory, and then kill that process so you can start “clean” with the next run. Start-Process starts a process and returns a reference to the process object; Get-Process gets a process and has properties to cover Virtual Memory, Working Set, Pages Memory, Non-Paged Memory, and so on.

$results = Measure-Command { whatever }

Is how you’d capture the results. The properties of $results would contain the various execution data:

$results | Format-List *

Would display everything. You could then copy whatever metric you cared about into another variable, array, or whatever, depending on what you’re looking to do with it.

Yes, Measure-Command is what you want for the timing. Combine it with Measure-Object to get your average. For example to see how long it takes on average to execute Get-ChildItem with 1000 samples, do this.

1..1000 | ForEach-Object {
    Measure-Command {
        Get-ChildItem
    }
} | Measure-Object -Property TotalMilliseconds -Average

Results:

Count    : 1000
Average  : 2.3910028
Sum      : 
Maximum  : 
Minimum  : 
Property : TotalMilliseconds