Measure Time Taken By A Function And Don'T Understand Why Time Difference is Negative
I am trying to check how much time does a function takes to execute in my code :
I did this :
void foo()
{
int time = System.DateTime.Now.Millisecond;
// code of my function. do this, that, etc.
Console.WriteLine((System.DateTime.Now.Millisecond-time).ToString());
}
What i get is this :
-247
I don't understand why minus ?? & please tell me ways to measure time taken by a function. & If pro-filer is an option then please recommend me some simple option.
Note : Here I have shown a console app but in practice i need for a Web App in ASP.NET which may be n-tier arc开发者_运维技巧hitecture also.
Thanks
DateTime.Millisecond returns the millisecond part of the current date/time, not the milliseconds since some previous date/time.
Use a Stopwatch:
var stopwatch = Stopwatch.StartNew();
// ...
Console.WriteLine(stopwatch.ElapsedMilliseconds);
You appear to be using and subtracting the current millisecond
e.g.
- 2010-01-01 00:00:00:999 -> System.DateTime.Now.Millisecond is 999
- 2010-01-01 00:00:01:000 -> System.DateTime.Now.Millisecond is 000
000 - 999 = -999; not terribly useful!
Using DateTime.Now to profile isn't recommended anyway. If you're just trying to get an idea, you probably want to look at System.Diagnostics.Stopwatch:-
void Foo()
{
Stopwatch myStopWatch = StopWatch.StartNew()
// Your code goes here;
Console.WriteLine(myStopWatch.ElapsedMilliseconds);
}
For "real world" use, though, you're best using a profiler.
DateTime.Millisecond
returns the millisecond component of the current time.
In other words, it returns the total number of milliseconds mod 1,000.
For example, if you happen to get the property at the exact end of a second, it will be 0.
Instead, you should use the Stopwatch
class.
The Millisecond property returns the milliseconds component of the date, i.e. a number between 0
and 999
.
As others have said, you can use the StopWatch class, or you can call the DateTime.Subtract() method to obtain a TimeSpan instance, then use the TotalMilliseconds property of that instance to get the total elapsed milliseconds between your two times:
public void Foo()
{
DateTime then = DateTime.Now;
// ...
Console.WriteLine(DateTime.Now.Subtract(then).TotalMilliseconds);
}
You may want to use Stopwatch.
精彩评论