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.

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

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

稿源:Learn Powershell (源链) | 关于 | 阅读提示

本站遵循[CC BY-NC-SA 4.0]。如您有版权、意见投诉等问题,请通过eMail联系我们处理。
酷辣虫 » 综合技术 » Quick Hits: Create and Start a Stopwatch in One Line

喜欢 (0)or分享给?

专业 x 专注 x 聚合 x 分享 CC BY-NC-SA 4.0

使用声明 | 英豪名录