You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell脚本StopWatch计时结果异常问题求助

Hey there! Let's break down your two questions one by one, nice and clearly.

1. Why your timing is showing the wrong value (the core bug)

The issue boils down to using the wrong TimeSpan property to calculate total runtime. Right now you're grabbing $StopWatch.elapsed.minutes—but this property only returns the minutes portion of the time span, not the total minutes the script actually ran.

Here's a concrete example to explain:

  • If your script runs for 1 hour and 4 minutes (total 64 minutes), elapsed.minutes will spit out 4 (just the minutes part of the hour), not the full 64
  • If it runs exactly 30 minutes, it works fine (returns 30), but if it runs 2 hours 4 minutes, you'll still only get 4

That's why your email says 4 minutes while the actual runtime is closer to 30 (or more likely, 1 hour 4 minutes—maybe you misjudged the real duration, but the core problem is the property choice).

Fix it with TotalMinutes

To get the full total number of minutes the script ran, use $StopWatch.elapsed.TotalMinutes instead. This returns a floating-point number that includes the complete duration (e.g., 64.0 for 1h4m, 29.98 for 29m59s).

If you want a clean integer for your email, round it or cast it:

# Round to the nearest whole minute
$TotalMinutes = [math]::Round($StopWatch.Elapsed.TotalMinutes)
# Or just take the integer portion (drops seconds entirely)
$TotalMinutes = [int]$StopWatch.Elapsed.TotalMinutes

Swap that into your script, and your email will show the real runtime from now on.


2. How StopWatch.Elapsed works under the hood

Great question! Yes, every time you access Elapsed, the StopWatch doesn't just pull a pre-stored number—it calculates the duration on the fly by:

  1. Reading the current value of the system's high-resolution performance counter (if your system supports it)
  2. Subtracting the counter value that was recorded when you called Start()

This is why StopWatch is more reliable than using DateTime comparisons: it's not affected by system time changes (like NTP sync adjusting the clock). Only if your system doesn't support high-resolution counters will it fall back to using system time for calculations.


内容的提问来源于stack exchange,提问作者Ochuse

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:40:19