-4

I tried the following code in a method:

Trace.Write("START "+Datetime.now);
//DATABASE METHOD CALL 
SaveData();
Trace.Write("END "+Datetime.now);

And I calculate the time in output window manually.

How do I use stopwatch (start/reset/stop) to get the correct execution time?

Nick Udell
  • 2,420
  • 5
  • 44
  • 83
Neo
  • 15,491
  • 59
  • 215
  • 405
  • You mean you don't know how to instantiate a class and invoke its methods? Your profile says you are experienced with c# – MikeSW Apr 23 '14 at 15:22
  • This is an obvious case of RTFM. http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx – tnw Apr 23 '14 at 15:22
  • Try this: http://stackoverflow.com/questions/14019510/calculate-the-execution-time-of-a-method – Lex Webb Apr 23 '14 at 15:23
  • Wow... for a user with fairly decent rep this is just appalling... A very simple Google search would have yielded many results for this. And then you go and mark your own question as a duplicate. – Evan L Apr 23 '14 at 15:40
  • yea i know but question not posted by me – Neo Apr 23 '14 at 15:43
  • @ashish, what do you mean "question not posted by me"? – gunr2171 Apr 23 '14 at 16:27

3 Answers3

6

Create an instance of Stopwatch by Stopwatch.StartNew, execute your method. Stop the Stopwatch and then get ElapsedMilliseconds like:

Stopwatch stopwatch = Stopwatch.StartNew();
SaveData();
stopwatch.Stop();
Trace.Write("Time in Millisecond:  " + stopwatch.ElapsedMilliseconds);

Remember to include using System.Diagnostics;

Habib
  • 219,104
  • 29
  • 407
  • 436
2

Use the Stopwatch class:

    // Create new stopwatch
    Stopwatch stopwatch = new Stopwatch();

    // Begin timing
    stopwatch.Start();

    // Do something
    for (int i = 0; i < 1000; i++)
    {
        Thread.Sleep(1);
    }

    // Stop timing
    stopwatch.Stop();

    // Write result
    Console.WriteLine("Time elapsed: {0}",
        stopwatch.Elapsed);
Amir Popovich
  • 29,350
  • 9
  • 53
  • 99
2

As per msdn:

Stopwatch stopWatch = new Stopwatch();
stopWatch.Start();
Thread.Sleep(10000);
stopWatch.Stop();
// Get the elapsed time as a TimeSpan value.
TimeSpan ts = stopWatch.Elapsed;

StopWatch

Ric
  • 12,855
  • 3
  • 30
  • 36