We often needCodeConfirms the execution efficiency of a method. For example, we have the following method:
Static void run ()
{
For (INT I = 0; I <1000; I ++)
{
Console. Write (I );
Thread. Sleep (5 );
}
}
We want to know how much time it takes to execute this method. The traditional method is to record the current time before the method is executed, and then record another time at the end, and then let them subtract it, like the following:
Datetime starttime = datetime. now;
Run ();
Timespan span = datetime. Now. Subtract (starttime );
Console. writeline ("execution time: {0} millisecond", span. milliseconds );
Console. Read ();
This is probably the case, right? Very familiar
However, the result is not very accurate. Sometimes (if the time is short), it may not be counted.
Starting from. NET 2.0, a special type is added to the system. Diagnostics namespace, called stopwatch, which makes it easier to do such a thing.
Stopwatch watch = new stopwatch ();
Watch. Start (); // The code can also be abbreviated as stopwpu watch = stopwatch. startnew ()
Run (); // execute this method
Watch. Stop ();
Console. writeline ("execution time: {0} seconds", watch. elapsedmilliseconds/1000.0f );
Console. Read ();
It looks good, isn't it?
The code can also be transformed in the next step. With the extension method of C #3.0, We can compile a type
Static class actionextension
{
Public static string profiler (this action func, int runcount)
{
Stopwatch watch = stopwatch. startnew (); // create a listener
For (INT I = 0; I <runcount; I ++)
{
Func (); // execute a method
}
Watch. Stop ();
Float sec = watch. elapsedmilliseconds/1000.0f;
Float freq = SEC/runcount;
Return string. format ("total execution time: {0} seconds, total execution times: {1}, average execution time: {2} seconds", SEC, runcount, freq );
}
}
This type means that the original action type is extended (this is a delegate: Delegate ). Add a profiler Method for it to return the execution time of a specific method
Action Act = run; // create a delegate pointing to the run Method
Console. writeline (Act. profiler (10); // execute 10 times for this run Method
Console. Read ();
In this way, you can