15

Does System.Diagnostics.Stopwatch count time during computer stand by?

Evgenyt
  • 10,201
  • 12
  • 40
  • 44
  • Interesting question, I've only ever used Stopwatch for poor-man's profiling so this never occurred to me. – Davy8 Dec 28 '11 at 13:18
  • 4
    Good question.... try it and let us know :) –  Dec 28 '11 at 13:18
  • As you can tell from the answer, this is implementation specific behavior. The counter is wrapped by the operating system's Hardware Abstraction Layer, giving hardware designers plenty of options to cut pennies. – Hans Passant Dec 28 '11 at 14:40

2 Answers2

3

Actually, after a little testing it does appear to be counting, but it was way off. This is what I did:

  1. Wrote the below code
  2. Ran it, and immediately put my computer in Sleep mode
  3. Waited 10 seconds and brought my computer back up

The result was a shocking Elapsed time of over 4 minutes. Way off. So I wouldn't use this as any sort of benchmark.

Here's the code I used:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;

namespace TestingCode
{
    class Program
    {
        static void Main(string[] args)
        {
            Stopwatch testing = new Stopwatch();

            testing.Start();

            Console.WriteLine("Press any key to stop timer");
            Console.ReadKey();

            testing.Stop();

            Console.WriteLine("Elapsed: {0}", testing.Elapsed);

            Console.WriteLine("Done!!");
            Console.ReadKey();
        }
    }
}
3

Yes it does.

Looking at the code in Reflector shows that if it is not Stopwatch.IsHighResolution, then it will use the tick count (in my environment, the value was false so it will use DateTime.UtcNow.Ticks):

public void Start()
{
    if (!this.isRunning)
    {
        this.startTimeStamp = GetTimestamp();
        this.isRunning = true;
    }
}



public static long GetTimestamp()
{
    if (IsHighResolution)
    {
        long num = 0L;
        SafeNativeMethods.QueryPerformanceCounter(out num);
        return num;
    }
    return DateTime.UtcNow.Ticks;
}
Aliostad
  • 80,612
  • 21
  • 160
  • 208