0

The main logic of a utility tool is in a function like this:

private void Run()
{
    DateTime startTime = DateTime.Now;
    Prepare();
    Search();
    Process();
    DateTime endTime = DateTime.Now;
    TimeSpan duration = endTime.Subtract(startTime);
    Console.WriteLine("Run took {0:00}:{1:00}:{2:00}",
        (int)duration.TotalHours, duration.Minutes, duration.Seconds);
}

When I run this I can see with my own eyes it is taking at least 5 seconds (Process() method spews console output which I can observe happening for 5-6s). But it reports "Run took 00:00:01".

I don't expect time to have microsecond precision but why is it so totally inaccurate here?

Update: Following advice I also ran a StopWatch over the same period and compared against subtracting two DateTime, and also debugged the code. The two methods agree to a fraction of a second... StopWatch in the debugger had 1139 milliseconds. My hypothesis is that somehow time writing to the console is not included but I have no way to back that up (or disprove it).

Mr. Boy
  • 60,845
  • 93
  • 320
  • 589

5 Answers5

2

To become confident in what you see is what really happens, write for test sake:

DateTime startTime = DateTime.Now;
Thread.Sleep(5000);
DateTime endTime = DateTime.Now;
TimeSpan duration = endTime.Subtract(startTime);
Console.WriteLine("Run took {0:00}:{1:00}:{2:00}",
        (int)duration.TotalHours, duration.Minutes, duration.Seconds);

Also, it's better to use Stopwatch class for your purposes

Dima
  • 6,721
  • 4
  • 24
  • 43
  • On longer runs it seems less inaccurate. I was even wondering if the console is lagging a few seconds behind the actual ed of the program... it writes a lot of lines to the console. I'll maybe compare `StopWatch` and see if the same results are seen. – Mr. Boy Mar 13 '13 at 12:01
2

I doubt that the problem is with DateTime. Likely, the program finished and sent the output to the console buffer, which is taking its sweet time actually displaying it. What you're seeing is output lag.

Jim Mischel
  • 131,090
  • 20
  • 188
  • 351
1

Why not use Stopwatch?

Stopwatch ss = new Stopwatch();
ss.Start();
// Some quantity of work..... 
ss.Stop();

Console.WriteLine("Elapsed time: {0}", ss.Elapsed.TotalMilliseconds);
Travis G
  • 1,592
  • 1
  • 13
  • 18
0

DateTime isn't very accurate for this kind of measurement. You should use the stopwatch class.

http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx

stevepkr84
  • 1,637
  • 2
  • 13
  • 23
0
DateTime startTime = DateTime.Now;
Thread.Sleep(5000);
DateTime endTime = DateTime.Now;
TimeSpan duration = endTime.Subtract(startTime);
Console.WriteLine(duration.Seconds);

Prints "5". Are you sure your test case is what it is?

CodeCaster
  • 147,647
  • 23
  • 218
  • 272