Simple time profiling - strange times

I am trying to profile my code to check how long it takes to execute some parts of my code.

I've wrapped my most time consuming piece of code like this:

DateTime start = DateTime.Now;
...
... // Here comes the time-consuming part
... 
Console.WriteLine((DateTime.Now - start).Miliseconds);

      

The program executes this part of the code for a couple of seconds (about 20 seconds), but in the console I get the result in about 800 milliseconds. Why is this so? What am I doing wrong?

+2


a source to share


4 answers


Are you sure you want the TotalMilliseconds property ? Milliseconds

returns the millisecond time component, not the actual length of the interval in milliseconds.



However, you probably want to use a stopwatch (as others have said) as it will be more accurate.

+8


a source


Try using the Stopwatch class . It was designed for this purpose.



Stopwatch sw = Stopwatch.StartNew();
// ...
// Here comes the time-consuming part
// ...
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);

      

+11


a source


This is a much better way to profile your code.

var result = CallMethod(); // This will JIT the method
var sw = Stopwatch.StartNew();
for (int i = 0; i < 5; i++)
{
    result = CallMethod();
}
sw.Stop();
Console.WriteLine(result);
Console.WriteLine(TimeSpan.FromTick(sw.ElapsedTicks / 5));

      

+3


a source


If you reference a property TotalMilliseconds

, you will get the result you were looking for. But I think the other answers recommend Stopwatch

being a best practice.

0


a source







All Articles