SoFunction
Updated on 2025-03-08

Use and instructions for Stopwatch in C#

Use of C# Stopwatch

What is Stopwatch

Stopwatch: Provides a set of methods and properties that accurately measure runtime.

When using it, you need to refer to the namespace:.

Simple use of Stopwatch

//Create a Stopwatch instanceStopwatch sw = new Stopwatch();
//Start timing();
for (int i = 0; i < 100; i++)
{
  (i);
}
//Stop timing();
("Time to use:" +  + "");
//Reset Stop the time interval measurement and reset the run time to 0();
("Time to use:" +  + "");
//Restart Stop the time interval measurement and reset the run time to 0, and then start measuring the run time again();
for (int i = 0; i < 100; i++)
{
  (i);
}
();
//Get the total running time (in milliseconds) measured by the current instance("Time to use:" +  + "");
//Get the total running time measured by the current instance("Time to use:"+); 
//Get the total running time measured by the current instance (expressed by the timer scale).();
();
//Using StartNew, it is equivalent to having been instantiated and starting the timingStopwatch sw=();
for (int i = 0; i < 100; i++)
{
  (i);
}
();
//Get the total running time (in milliseconds) measured by the current instance("Time to use:" +  + "");
//Get the total running time measured by the current instance("Time to use:"+); 
();

C# uses Stopwatch to measure run time accurately

Generally, the measurement time interval uses the current attributes of the instance. If you want to accurately measure the running time of an operation, you can only use the Stopwatch class to time.

The Stopwatch timing accuracy depends on the hardware, and if the installed hardware and operating system support a high-resolution performance counter, the Stopwatch class will use this counter to measure the runtime. Otherwise, the Stopwatch class will use a system timer to measure the run time.

Measure the running time of the time consuming operation

            Stopwatch stopWatch = new Stopwatch();
            ();
            (5000); // Time-consuming operation            ();
            

            // Take the elapsed time as the TimeSpan value            TimeSpan ts = ;
            // Format and display time value            string elapsedTime = ("{0:00}:{1:00}:{2:00}.{3:000}-{4:000}", , , , , ( * 100 / 1000)%1000);
            ("RunTime " + elapsedTime);

            // Use elapsed time as milliseconds            long mSeconds = ;
            ("RunTime(ms) " + mSeconds);

            // Get the timer scale of elapsed time            // You can also use () to obtain 1 Ticks value before and after the time-consuming operation, and then subtract it to obtain the timer scale for the time-consuming operation.            // The timer uses different timing methods, and the time units of ticks are different            long tick = ;
            ("RunTime(tick) " + tick);

            if ()
            {
                // The timer scale is the number of high-performance timer ticks                ("Timed using system high resolution performance counters:");
                ("  RunTime(ns) " +tick* ((1000L * 1000L * 1000L)/ ));
            }
            else
            {
                // Timer scale is the current property of the instance                ("Use DateTime class to time:");
                ("  RunTime(ns) " + tick * 100);
            }

Check out how the Stopwatch timer is timed

        /// <summary>
        /// Display timer properties        /// </summary>
        public static void DisplayTimerProperties()
        {
            // Display timer frequency and resolution            if ()
            {
                ("Operation uses system high-resolution performance counter to time");
            }
            else
            {
                ("Operation uses DateTime class to time");
            }

            long frequency = ;
            ("  Timer frequency,Units are ticking per second = {0}",
                frequency);
            long nanosecPerTick = (1000L * 1000L * 1000L) / frequency;
            ("  The timer resolution is {0} Nanoseconds/Tick",
                nanosecPerTick);
        }

Attached a test example on the official website

        private static void TimeOperations()
        {
            long nanosecPerTick = (1000L * 1000L * 1000L) / ;
            const long numIterations = 10000;

            // Define the operation title name            String[] operationNames = {"operate: (\"0\")",
                                           "operate: (\"0\")",
                                           "operate: (\"a\")",
                                           "operate: (\"a\")"};
            ();
            ("Note:1ticks=100ns,1s=1000ms,1ms=1000us,1us=1000ns");

            // Four different implementations of parsing integers from strings            for (int operation = 0; operation <= 3; operation++)
            {
                // Define the 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 discarded as it may distort the average time.                for (int i = 0; i <= numIterations; i++)
                {
                    long ticksThisTime = 0;
                    int inputNum;
                    Stopwatch timePerParse;

                    switch (operation)
                    {
                        case 0:
                            // Use the try-catch statement to analyze valid integers                            // Start a new stopwatch timer                            timePerParse = ();
                            try
                            {
                                inputNum = ("0");
                            }
                            catch (FormatException)
                            {
                                inputNum = 0;
                            }

                            // Stop the timer and save the timing ticks used for the operation
                            ();
                            ticksThisTime = ;
                            break;
                        case 1:                           
                            timePerParse = ();
                            if (!("0", out inputNum))
                            {
                                inputNum = 0;
                            }
                            ();
                            ticksThisTime = ;
                            break;
                        case 2:                            
                            timePerParse = ();
                            try
                            {
                                inputNum = ("a");
                            }
                            catch (FormatException)
                            {
                                inputNum = 0;
                            }
                            ();
                            ticksThisTime = ;
                            break;
                        case 3:                           
                            timePerParse = ();
                            if (!("a", out inputNum))
                            {
                                inputNum = 0;
                            }                            
                            ();
                            ticksThisTime = ;
                            break;
                        default:
                            break;
                    }
                    // Skip the time of the first operation in case it causes one-time performance degradation.                    if (i == 0)
                    {
                        ();
                        ();
                    }
                    else
                    {
                        // Update the operation statistics of iterations 1-10001.                        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 statistics for 10,000 iterations                ();
                milliSec = ;

                ();
                ("{0} statistics:", operationNames[operation]);
                ("  The slowest time:  The{0}/{1}次operate,Time is{2} ticks",
                    indexSlowest, numIterations, maxTicks);
                ("  The fastest time:  The{0}/{1}次operate,Time is{2} ticks",
                    indexFastest, numIterations, minTicks);
                ("  Average time:  {0} ticks = {1} ns",
                    numTicks / numIterations,
                    (numTicks * nanosecPerTick) / numIterations);
                ("  {0} 次operate的总时间: {1} ms",
                    numIterations, milliSec);
            }
        }

Summarize

The above is personal experience. I hope you can give you a reference and I hope you can support me more.