Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple time profiling - strange times

Tags:

c#

I'm 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 part of the code in something like that:

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

The program is executing this part of code for couple of seconds (about 20 s) but in console I get the result of something about 800 miliseconds. Why is that so? What am I doing wrong?

like image 594
Gacek Avatar asked Oct 16 '25 03:10

Gacek


2 Answers

Try using the Stopwatch class for this. It was intended for this exact purpose.

Stopwatch sw = Stopwatch.StartNew();
// ...
// Here comes the time-consuming part
// ...
sw.Stop();
Console.WriteLine(sw.ElapsedMilliseconds);
like image 105
Reed Copsey Avatar answered Oct 19 '25 05:10

Reed Copsey


Are you actually wanting the TotalMilliseconds property? Milliseconds returns the milliseconds component of the timespan, not the actual length of the timespan in milliseconds.

That said, you probably want to use Stopwatch (as the others said) since it will be more accurate.

like image 32
Zach Johnson Avatar answered Oct 19 '25 05:10

Zach Johnson



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!