To customize the class calctimingfor the execution time of a statistic code, consider:
Garbage collection is not allowed during the execution of the statistics. That is, before the statistics code execution time, let the GC complete garbage collection.
Ensure that the execution time of the code in the current process is counted.
Write the following code:
public class calctiming { TimeSpan startTime; Private TimeSpan endTime; TimeSpan duration; Public calctiming () { startTime = new TimeSpan (0); Duration = new TimeSpan (0); } public void StartTime () { //enforces garbage collection for all generations GC. Collect (); Suspends the thread, and the finalizer thread empties the queue until the GC. WaitForPendingFinalizers (); The start time of the user running the code StartTime = process.getcurrentprocess (). userprocessortime; } The statistics of the Code execution time public void StopTime () { endTime = process.getcurrentprocess (). Userprocessortime; Duration = Endtime.subtract (startTime); } Returns the time spent by the code execution of a statistic public TimeSpan Result () { return duration; } }
Using the above calctiming class, statistics show the consumption time of the array:
Class program { static void Main (string[] args) { int[] nums = new int[100000]; Buildarray (nums); Calctiming calctime= new Calctiming (); Calctime.starttime (); Displaynums (nums); Calctime.stoptime (); Console.WriteLine (String. Format ("shared time: {0} ms", Calctime.result (). TotalMilliseconds)); Console.read (); } static void Buildarray (int[] arr) {for (int i = 0; i < 100000; i++) arr[i] = 1; } static void Displaynums (int[] arr) {for (int i = 0; I <= arr. GetUpperBound (0); i++) Console.Write (Arr[i] + ""); } }
Summarize, in the next use C # to describe all data structures, the time spent in statistics, the use of calctiming objects.