The first method: System.DateTime.Now
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceexample{ Public classProgram {Static voidMain (string[] args) { intsum=0; DateTime Beforedt = System.DateTime.Now; for(inti =0; I <100000; i++) {sum+=i; } DateTime Afterdt = System.DateTime.Now;//gets a System.DateTime object that is set to the current date and time on this computer, expressed as local time TimeSpan dt = afterdt.subtract (Beforedt);//a timespan represents a time interval in which Subtract () subtracts the specified time and date from this instanceConsole.WriteLine ("program time: ' {0} ' seconds", DT); Console.ReadLine (); } }}
The second method: Stopwatch
usingSystem;usingSystem.Collections.Generic;usingSystem.Diagnostics;usingSystem.Linq;usingSystem.Text;namespaceexample{ Public classProgram {Static voidMain (string[] args) { intsum=0; Stopwatch SW = new Stopwatch ();//Stopwatch provides a set of methods and properties that can be used to accurately measure run timesSW. Start (); for(inti =0; I <100000; i++) {sum+=i; } SW. Stop (); TimeSpan DT = SW. Elapsed;//gets the total elapsed time measured by the current instanceConsole.WriteLine ("program time: ' {0} ' seconds", DT); Console.ReadLine (); } }}
C # COMPUTE code Execution time-consuming