0

I would like to test the time required by certain methods and SQL queries in my code. I've tried doing the following:

DateTime start = DateTime.Now;

//Do something

DateTime end = DateTime.Now;

TimeSpan ts = end - start;

int millis = ts.Milliseconds;

But I just don't feel that this is the right way of doing it. I often get back a value of 1 for some methods and values like 200 for others, are there any accurate ways to measure and record this kind of thing?

PaulG
  • 6,920
  • 12
  • 54
  • 98

2 Answers2

7

Use Stopwatch class.

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
//your work
stopWatch.Stop();
L.B
  • 114,136
  • 19
  • 178
  • 224
0

Provides a set of methods and properties that you can use to accurately measure elapsed time using Stopwatch class. That is really good and can be used to measure and compare algorithm run time.

    using System.Diagnostics;
    // ...

    Stopwatch sw = new Stopwatch();

    sw.Start();

    // ...

    sw.Stop();

    Console.WriteLine("Elapsed={0}",sw.Elapsed);
Thilina H
  • 5,754
  • 6
  • 26
  • 56