Reputation: 1202
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?
Upvotes: 1
Views: 376
Reputation: 3928
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
Upvotes: 3
Reputation: 374
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.
Upvotes: 0
Reputation: 587
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();
Upvotes: 1