stopwatch in C# using DateTime and TimeSpan

I write a class called stopwatch and their two method(Start() and Stop())in it. Every time I Start and Stop,I should get the TimeSpan for the interval. But every time I run it, I always get the TimeSpan 00:00:00. Where is wrong? Here are my code:

class Stopwatch
    {
        private DateTime _start;
        private DateTime _stop;
        private bool _running;

        public void Start()
        {
            if (!_running)
            {
                _running = true;
                _start = DateTime.Now;
            }
        }
        public TimeSpan Stop()
        {
            if (_running)
            {
                _stop = DateTime.Now;
                _running = false;
            }
            return (_stop - _start);
        }

run in main method:

static void Main(string[] args)
{
    Console.WriteLine("Stopwatch application");
    Console.WriteLine("tap 'y' to start,'n' to stop,'q' to quit.");
    while (true)
    {
        Console.WriteLine("tap 'y' to start,'n' to stop,'q' to quit.");
        var input = Console.ReadLine();
        var stopWatch = new Stopwatch();
        if (input == "y")
        {
            Console.WriteLine("start");
            stopWatch.Start();
        }
        if (input == "n")
        {
            Console.WriteLine("stop");
            Console.WriteLine(stopWatch.Stop().ToString("G"));
        }
        if (input == "q") break;
    }
}

One solution I've tried is, replace all the input by Cosole.ReadLine(), it works well. But where is wrong with my original code?

Jon Skeet
people
quotationmark

You're creating a new instance of Stopwatch on each iteration - which means that _running will always be false when you call Stop.

In addition:

  • You should be using DateTime.UtcNow instead of DateTime.Now, otherwise you'll see a "change" of -1 hour or 1 hour if DST starts or ends
  • You don't need your Stopwatch class at all - you should use System.Diagnostics.Stopwatch instead. That often has a higher precision and isn't affected by things that change the system clock. It's precisely designed for this kind of thing.

So something like (adjusted for style in a couple of places):

var stopwatch = new Stopwatch();
while (true)
{
    Console.WriteLine("Tap 'y' to start, 'n' to stop, or 'q' to quit.");
    switch (Console.ReadLine())
    {
        case "y":
            Console.WriteLine("start");
            // Resets *and* starts if necessary
            stopwatch.Restart();
            break;
        case "n":
            Console.WriteLine("stop");
            stopwatch.Stop();
            Console.WriteLine(stopWatch.Elapsed);
            break;
        case "q":
            return;
    }
}

people

See more on this question at Stackoverflow