.NET System.Diagnostics.Stopwatch issue (returns values too low)

前端 未结 7 1114
眼角桃花
眼角桃花 2021-02-13 23:14

On my computer the Stopwatch is returning values way too low. For example, 200 ms when I specified Thread.Sleep(1000). The program is supposed to wait 1 second. I a

7条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-13 23:53

    I know this an old question, but I thought I'd provide my 2 cents after struggling with the same problem:

    I started looking at the Frequency as suggested by @AllonGuralnek and it did provide the accurate time in seconds, but it dropped the remaining milliseconds which I also wanted to capture.

    Anyway, after a lot of back and forth and not getting anywhere with this, I noticed that the sw.Elapsed had a Ticks property and this one provided me with the accurate number of ticks and once converted back it provided me with an accurate time.

    Code wise, this is what I ended up with:

    Stopwatch sw = new Stopwatch();
    sw.Start();
    
    ... DO WORK
    
    sw.Stop();
    
    long elapsedTicks = sw.Elapsed.Ticks;
    Debug.WriteLine(TimeSpan.FromTicks(elapsedTicks).ToString());
    

    When running a test, calling:

    • sw.Elapsed.ToString() : "00:00:11.6013029"

    • sw.ElapsedTicks : Returns "40692243" and converts to "00:00:04.0692243" when calling TimeSpan.FromTicks(sw.ElapsedTicks).ToString() which is inaccurate.

    • sw.Elapsed.Ticks : Returns "116013029" and converts to "00:00:11.6013029" when calling TimeSpan.FromTicks(sw.Elapsed.Ticks).ToString() which accurate.

    While I may be missing something, I feel it doesn't make sense that sw.ElaspedTicks returns a different value than sw.Elapsed.Ticks, so if someone wants to shed some light on this, please do, but from my point of view, I see it as a bug and if not, at least it feels very inconsistent!.

    NOTE: Calling sw.ElapsedTicks / Stopwatch.Frequency returns 11 (i.e. seconds) but as I said, it drops the milliseconds which is no use to me.

提交回复
热议问题