Quick Hits: Create and Start a Stopwatch in One Line

Ok, so this is a pretty trivial thing but I happened to stumble across this while doing some work on figuring out a bottleneck in one of my scripts.

Essentially, I set up a StopWatch to see how long it takes to complete a chunk of code and as you may or may not know, you usually set this up by instantiating the object using New-Object and then using the Start() method to kick it off, like this:

$StopWatch = New-Object System.Diagnostics.Stopwatch
$StopWatch.Start()
$StopWatch.Elapsed
$StopWatch.Stop()

We see the object being created, then started and stopped as well as viewing the elapsed time.

image

Ok, not really a lot of code here, but I’m always curious to see how much shorter the code could go, and sure enough, there is a static method on the type called StartNew() which not only creates the object but also starts the stopwatch for you. Now all you have to do is monitor the elapsed time and stop it when you are done with it.

$StopWatch = [System.Diagnostics.Stopwatch]::StartNew()
#Wait a bit
$StopWatch.Stop()
$StopWatch.Elapsed

image

Nothing spectacular here or life changing, but just a slightly shorter way to perform this particular task. Enjoy!

This entry was posted in powershell and tagged , , . Bookmark the permalink.

Leave a comment