最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

C#使用Stopwatch實(shí)現(xiàn)計(jì)時(shí)功能

 更新時(shí)間:2024年03月26日 14:42:18   作者:追逐時(shí)光者  
在 C# 中,Stopwatch 類是用于測(cè)量經(jīng)過(guò)的時(shí)間的工具類,提供了高精度的計(jì)時(shí)功能,本文主要介紹了C#如何使用Stopwatch實(shí)現(xiàn)計(jì)時(shí)功能,需要的可以參考下

前言

在 C# 中,Stopwatch 類是用于測(cè)量經(jīng)過(guò)的時(shí)間的工具類,提供了高精度的計(jì)時(shí)功能。Stopwatch 類位于 System.Diagnostics 命名空間中。通常情況下,使用 Stopwatch 的流程是創(chuàng)建一個(gè) Stopwatch 對(duì)象,然后調(diào)用 Start 方法開始計(jì)時(shí),執(zhí)行需要測(cè)量時(shí)間的代碼,最后調(diào)用 Stop 方法停止計(jì)時(shí),并通過(guò) Elapsed 屬性獲取經(jīng)過(guò)的時(shí)間。

Stopwatch 類中常用的方法包括

Start():開始計(jì)時(shí)。

Stop():停止計(jì)時(shí)。

Reset():重置計(jì)時(shí)器。

Restart():重啟計(jì)時(shí)器。

Elapsed:獲取經(jīng)過(guò)的時(shí)間(Elapsed 屬性返回一個(gè) TimeSpan 對(duì)象,表示自 Stopwatch 實(shí)例開始計(jì)時(shí)以來(lái)經(jīng)過(guò)的時(shí)間。你可以通過(guò)訪問 Elapsed 屬性來(lái)獲取經(jīng)過(guò)的時(shí)間)

ElapsedMilliseconds:回一個(gè) long 值,表示自 Stopwatch 實(shí)例開始計(jì)時(shí)以來(lái)經(jīng)過(guò)的毫秒數(shù)。

ElapsedTicks:返回一個(gè) long 值,表示自 Stopwatch 實(shí)例開始計(jì)時(shí)以來(lái)經(jīng)過(guò)的計(jì)時(shí)周期數(shù)。這個(gè)值通常用于更精確的時(shí)間測(cè)量。

使用示例

using System;
using System.Diagnostics;
 
class Program
{
    static void Main()
    {
        Stopwatch stopwatch = new Stopwatch();
 
        stopwatch.Start();
 
        // 模擬耗時(shí)操作
        for (int i = 0; i < 1000000; i++)
        {
            // do something
        }
 
        stopwatch.Stop();
 
        Console.WriteLine($"經(jīng)過(guò)的時(shí)間: {stopwatch.Elapsed}");
    }
}

使用總結(jié)

通過(guò)使用 Stopwatch 類,開發(fā)人員可以更準(zhǔn)確地測(cè)量代碼執(zhí)行的時(shí)間,進(jìn)行性能分析和優(yōu)化,從而提升應(yīng)用程序的性能表現(xiàn)。

知識(shí)補(bǔ)充

除了上文的內(nèi)容,小編還為大家整理一些Stopwatch類的其他應(yīng)用,希望對(duì)大家有所幫助

C# StopWatch 實(shí)現(xiàn)程序精準(zhǔn)計(jì)時(shí)

下面的示例演示如何使用Stopwatch類來(lái)確定應(yīng)用程序的執(zhí)行時(shí)間。

using System;
using System.Diagnostics;
using System.Threading;
class Program
{
    static void Main(string[] args)
    {
        Stopwatch stopWatch = new Stopwatch();
        // 開始
        stopWatch.Start();
		
		// 程序執(zhí)行
        Thread.Sleep(10000);
        
        // 結(jié)束
        stopWatch.Stop();
        
        // 獲取作為 TimeSpan 值的經(jīng)過(guò)時(shí)間。
        TimeSpan ts = stopWatch.Elapsed;

        // 格式化
        string elapsedTime = String.Format("{0:00}:{1:00}:{2:00}.{3:00}",
            ts.Hours, ts.Minutes, ts.Seconds,
            ts.Milliseconds / 10);

	    // 打印時(shí)間差
        Console.WriteLine("RunTime " + elapsedTime);
    }
}

Stopwatch還可以來(lái)計(jì)算性能數(shù)據(jù),示例代碼如下:

using System;
using System.Diagnostics;

namespace StopWatchSample
{
    class OperationsTimer
    {
        public static void Main()
        {
            DisplayTimerProperties();

            Console.WriteLine();
            Console.WriteLine("Press the Enter key to begin:");
            Console.ReadLine();
            Console.WriteLine();

            TimeOperations();
        }

        public static void DisplayTimerProperties()
        {
            // Display the timer frequency and resolution.
            if (Stopwatch.IsHighResolution)
            {
                Console.WriteLine("Operations timed using the system's high-resolution performance counter.");
            }
            else
            {
                Console.WriteLine("Operations timed using the DateTime class.");
            }

            long frequency = Stopwatch.Frequency;
            Console.WriteLine("  Timer frequency in ticks per second = {0}",
                frequency);
            long nanosecPerTick = (1000L*1000L*1000L) / frequency;
            Console.WriteLine("  Timer is accurate within {0} nanoseconds",
                nanosecPerTick);
        }

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

            // Define the operation title names.
            String [] operationNames = {"Operation: Int32.Parse(\"0\")",
                                           "Operation: Int32.TryParse(\"0\")",
                                           "Operation: Int32.Parse(\"a\")",
                                           "Operation: Int32.TryParse(\"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 = Int64.MaxValue;
                int indexFastest = -1;
                int indexSlowest = -1;
                long milliSec = 0;

                Stopwatch time10kOperations = Stopwatch.StartNew();

                // 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 = Stopwatch.StartNew();

                            try
                            {
                                inputNum = Int32.Parse("0");
                            }
                            catch (FormatException)
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.

                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;
                        case 1:
                            // Parse a valid integer using
                            // the TryParse statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            if (!Int32.TryParse("0", out inputNum))
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;
                        case 2:
                            // Parse an invalid value using
                            // a try-catch statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            try
                            {
                                inputNum = Int32.Parse("a");
                            }
                            catch (FormatException)
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;
                        case 3:
                            // Parse an invalid value using
                            // the TryParse statement.

                            // Start a new stopwatch timer.
                            timePerParse = Stopwatch.StartNew();

                            if (!Int32.TryParse("a", out inputNum))
                            {
                                inputNum = 0;
                            }

                            // Stop the timer, and save the
                            // elapsed ticks for the operation.
                            timePerParse.Stop();
                            ticksThisTime = timePerParse.ElapsedTicks;
                            break;

                        default:
                            break;
                    }

                    // Skip over the time for the first operation,
                    // just in case it caused a one-time
                    // performance hit.
                    if (i == 0)
                    {
                        time10kOperations.Reset();
                        time10kOperations.Start();
                    }
                    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.

                time10kOperations.Stop();
                milliSec = time10kOperations.ElapsedMilliseconds;

                Console.WriteLine();
                Console.WriteLine("{0} Summary:", operationNames[operation]);
                Console.WriteLine("  Slowest time:  #{0}/{1} = {2} ticks",
                    indexSlowest, numIterations, maxTicks);
                Console.WriteLine("  Fastest time:  #{0}/{1} = {2} ticks",
                    indexFastest, numIterations, minTicks);
                Console.WriteLine("  Average time:  {0} ticks = {1} nanoseconds",
                    numTicks / numIterations,
                    (numTicks * nanosecPerTick) / numIterations );
                Console.WriteLine("  Total time looping through {0} operations: {1} milliseconds",
                    numIterations, milliSec);
            }
        }
     }
}

Stopwatch實(shí)現(xiàn)對(duì)程序運(yùn)行的精確計(jì)時(shí)

demo

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace StopWatchDemo
{
    class Program
    {
       
        static void Main(string[] args)
        {
            int i = 6000000,m1= 0,m2=0;
            Stopwatch sw = new Stopwatch();
            sw.Start();
            for (int k = 0; k <= i; k++)
            {
                m1++;
            }
            Console.WriteLine(sw.ElapsedMilliseconds);
            sw.Restart();
            for (int k = 0; k <= i; k+=2) 
            {
                m2++;
            }
            sw.Stop();
            Console.WriteLine(sw.ElapsedMilliseconds);
            Console.ReadKey();
        }
    }
}

到此這篇關(guān)于C#使用Stopwatch實(shí)現(xiàn)計(jì)時(shí)功能的文章就介紹到這了,更多相關(guān)C# Stopwatch計(jì)時(shí)內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評(píng)論

成都市| 运城市| 仲巴县| 谢通门县| 尤溪县| 河池市| 古浪县| 外汇| 新田县| 河曲县| 民乐县| 依兰县| 天气| 西乌珠穆沁旗| 仁寿县| 北宁市| 福鼎市| 杭州市| 固镇县| 鸡西市| 临猗县| 东乌| 沭阳县| 青冈县| 温州市| 巩义市| 永新县| 定襄县| 读书| 公主岭市| 安徽省| 山丹县| 冷水江市| 通榆县| 唐海县| 江川县| 五常市| 鹤庆县| 自贡市| 时尚| 来凤县|