1

I try this:

Stopwatch timer = new Stopwatch();
timer.Start();

for (i = 0; i < 100; i++) {
    //do here some stuff
    Thread.Sleep(500);
}

timer.Stop();
TimeSpan ts = timer.Elapsed;
Console.WriteLine(ts.Milliseconds);

And it show me 49 milliseconds, but in fact it was performed in like 2 minutes. It's educational tusk and i have to consider sleep time. How can i do this?

InfernumDeus
  • 1,185
  • 1
  • 11
  • 33

3 Answers3

3

The Timespan.Milliseconds property returns the millisecond part of the timespan, after subtracting elapsed seconds, minutes, hours, etc. You probably want TimeSpan.TotalMilliseconds.

See this post for the explanation: C# Timespan Milliseconds vs TotalMilliseconds

Community
  • 1
  • 1
James
  • 3,551
  • 1
  • 28
  • 38
1

I think it is a unit problem, try getting ms directly from stopwatch, this worked for me:

    Stopwatch timer = new Stopwatch();
    timer.Start();

    for (int i = 0; i < 20; i++)
    {
        //do here some stuff
        Thread.Sleep(500);
    }

    timer.Stop();
    long ms =  timer.ElapsedMilliseconds;
    Console.WriteLine(ms);
    Console.ReadLine();
Noel
  • 567
  • 1
  • 4
  • 11
0

Use of Stopwatch will not be accurate, if you want a precise measurement of the execution of some code you will have to use the performance counters that's built into the operating system. Check this out.

Community
  • 1
  • 1
Utkarsh
  • 384
  • 3
  • 6
  • That post has no solution for accurately measuring elapsed time--in fact, performance counters have to use stopwatch ticks anyway. – James Feb 25 '15 at 05:02
  • Stopwatch uses the most accurate timing measurement available to the system. The underlying implementation uses QueryPerformanceCounter. The C# PerformanceCounter objects your post references do not measure anything--they are used to *report* measurements to outside observers, and they must be *given* the elapsed time using Stopwatch (or QueryPerformanceCounter). – James Feb 25 '15 at 05:30
  • [StopWatch](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) The Stopwatch measures elapsed time by counting timer ticks in the underlying timer mechanism. If the installed hardware and operating system support a high-resolution performance counter, then the Stopwatch class uses that counter to measure elapsed time. Otherwise, the Stopwatch class uses the system timer to measure elapsed time. why not use Stopwatch to profile methods. In conjunction they will yield desired result. – Utkarsh Feb 25 '15 at 05:30
  • The OP *is* using Stopwatch to profile--it's not working for him because he's using the wrong property. The use of PerformanceCounter objects you reference does *nothing* to help him measure the speed of his code. – James Feb 25 '15 at 05:32