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 to share
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 to share