Preface
In C#, the Stopwatch class is a tool class for measuring elapsed time, providing high-precision timing functions. The Stopwatch class is located in the namespace. Typically, the process of using Stopwatch is to create a Stopwatch object, then call the Start method to start the timing, execute the code that needs to measure the time, and finally call the Stop method to stop the timing, and obtain the elapsed time through the Elapsed property.
Common methods in the Stopwatch class include
Start(): Start timing.
Stop(): Stop timing.
Reset(): Reset the timer.
Restart(): Restart the timer.
Elapsed: Gets the elapsed time (The Elapsed property returns a TimeSpan object that represents the elapsed time since the Stopwatch instance starts to time. You can get the elapsed time by accessing the Elapsed property)
ElapsedMilliseconds: Returns a long value that represents the number of milliseconds elapsed since the Stopwatch instance starts to time.
ElapsedTicks: Returns a long value indicating the number of timing cycles elapsed since the Stopwatch instance starts to count. This value is usually used for more precise time measurements.
Example of usage
using System; using ; class Program { static void Main() { Stopwatch stopwatch = new Stopwatch(); (); // Simulation time-consuming operation for (int i = 0; i < 1000000; i++) { // do something } (); ($"Elapsed time: {}"); } }
Summary of use
By usingStopwatch
Class, developers can more accurately measure the time of code execution, perform performance analysis and optimization, thereby improving application performance performance.
Knowledge Supplement
C# StopWatch implements accurate program timing
The following example demonstrates how to use the Stopwatch class to determine the execution time of an application.
using System; using ; using ; class Program { static void Main(string[] args) { Stopwatch stopWatch = new Stopwatch(); // start (); // Program execution (10000); // Finish (); // Get the elapsed time as the TimeSpan value. TimeSpan ts = ; // Format string elapsedTime = ("{0:00}:{1:00}:{2:00}.{3:00}", , , , / 10); // Print time difference ("RunTime " + elapsedTime); } }
Stopwatch can also calculate performance data, the sample code is as follows:
using System; using ; namespace StopWatchSample { class OperationsTimer { public static void Main() { DisplayTimerProperties(); (); ("Press the Enter key to begin:"); (); (); TimeOperations(); } public static void DisplayTimerProperties() { // Display the timer frequency and resolution. if () { ("Operations timed using the system's high-resolution performance counter."); } else { ("Operations timed using the DateTime class."); } long frequency = ; (" Timer frequency in ticks per second = {0}", frequency); long nanosecPerTick = (1000L*1000L*1000L) / frequency; (" Timer is accurate within {0} nanoseconds", nanosecPerTick); } private static void TimeOperations() { long nanosecPerTick = (1000L*1000L*1000L) / ; const long numIterations = 10000; // Define the operation title names. String [] operationNames = {"Operation: (\"0\")", "Operation: (\"0\")", "Operation: (\"a\")", "Operation: (\"a\")"}; // Time four different implementations for parsing // an integer from a string. for (int operation = 0; operation <= 3; operation++) { // Define variables for operation statistics. long numTicks = 0; long numRollovers = 0; long maxTicks = 0; long minTicks = ; int indexFastest = -1; int indexSlowest = -1; long milliSec = 0; Stopwatch time10kOperations = (); // Run the current operation 10001 times. // The first execution time will be tossed // out, since it can skew the average time. for (int i=0; i<=numIterations; i++) { long ticksThisTime = 0; int inputNum; Stopwatch timePerParse; switch (operation) { case 0: // Parse a valid integer using // a try-catch statement. // Start a new stopwatch timer. timePerParse = (); try { inputNum = ("0"); } catch (FormatException) { inputNum = 0; } // Stop the timer, and save the // elapsed ticks for the operation. (); ticksThisTime = ; break; case 1: // Parse a valid integer using // the TryParse statement. // Start a new stopwatch timer. timePerParse = (); if (!("0", out inputNum)) { inputNum = 0; } // Stop the timer, and save the // elapsed ticks for the operation. (); ticksThisTime = ; break; case 2: // Parse an invalid value using // a try-catch statement. // Start a new stopwatch timer. timePerParse = (); try { inputNum = ("a"); } catch (FormatException) { inputNum = 0; } // Stop the timer, and save the // elapsed ticks for the operation. (); ticksThisTime = ; break; case 3: // Parse an invalid value using // the TryParse statement. // Start a new stopwatch timer. timePerParse = (); if (!("a", out inputNum)) { inputNum = 0; } // Stop the timer, and save the // elapsed ticks for the operation. (); ticksThisTime = ; break; default: break; } // Skip over the time for the first operation, // just in case it caused a one-time // performance hit. if (i == 0) { (); (); } else { // Update operation statistics // for iterations 1-10000. if (maxTicks < ticksThisTime) { indexSlowest = i; maxTicks = ticksThisTime; } if (minTicks > ticksThisTime) { indexFastest = i; minTicks = ticksThisTime; } numTicks += ticksThisTime; if (numTicks < ticksThisTime) { // Keep track of rollovers. numRollovers ++; } } } // Display the statistics for 10000 iterations. (); milliSec = ; (); ("{0} Summary:", operationNames[operation]); (" Slowest time: #{0}/{1} = {2} ticks", indexSlowest, numIterations, maxTicks); (" Fastest time: #{0}/{1} = {2} ticks", indexFastest, numIterations, minTicks); (" Average time: {0} ticks = {1} nanoseconds", numTicks / numIterations, (numTicks * nanosecPerTick) / numIterations ); (" Total time looping through {0} operations: {1} milliseconds", numIterations, milliSec); } } } }
Stopwatch implements accurate timing of program operation
demo
using System; using ; using ; using ; using ; using ; using ; namespace StopWatchDemo { class Program { static void Main(string[] args) { int i = 6000000,m1= 0,m2=0; Stopwatch sw = new Stopwatch(); (); for (int k = 0; k <= i; k++) { m1++; } (); (); for (int k = 0; k <= i; k+=2) { m2++; } (); (); (); } } }
This is the end of this article about C# using Stopwatch to implement timing function. For more related C# Stopwatch timing content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!