C#使用Stopwatch實(shí)現(xiàn)計時功能
前言
在 C# 中,Stopwatch 類是用于測量經(jīng)過的時間的工具類,提供了高精度的計時功能。Stopwatch 類位于 System.Diagnostics 命名空間中。通常情況下,使用 Stopwatch 的流程是創(chuàng)建一個 Stopwatch 對象,然后調(diào)用 Start 方法開始計時,執(zhí)行需要測量時間的代碼,最后調(diào)用 Stop 方法停止計時,并通過 Elapsed 屬性獲取經(jīng)過的時間。
Stopwatch 類中常用的方法包括
Start():開始計時。
Stop():停止計時。
Reset():重置計時器。
Restart():重啟計時器。
Elapsed:獲取經(jīng)過的時間(Elapsed 屬性返回一個 TimeSpan 對象,表示自 Stopwatch 實(shí)例開始計時以來經(jīng)過的時間。你可以通過訪問 Elapsed 屬性來獲取經(jīng)過的時間)
ElapsedMilliseconds:回一個 long 值,表示自 Stopwatch 實(shí)例開始計時以來經(jīng)過的毫秒數(shù)。
ElapsedTicks:返回一個 long 值,表示自 Stopwatch 實(shí)例開始計時以來經(jīng)過的計時周期數(shù)。這個值通常用于更精確的時間測量。
使用示例
using System; using System.Diagnostics; class Program { static void Main() { Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); // 模擬耗時操作 for (int i = 0; i < 1000000; i++) { // do something } stopwatch.Stop(); Console.WriteLine($"經(jīng)過的時間: {stopwatch.Elapsed}"); } }
使用總結(jié)
通過使用 Stopwatch
類,開發(fā)人員可以更準(zhǔn)確地測量代碼執(zhí)行的時間,進(jìn)行性能分析和優(yōu)化,從而提升應(yīng)用程序的性能表現(xiàn)。
知識補(bǔ)充
除了上文的內(nèi)容,小編還為大家整理一些Stopwatch類的其他應(yīng)用,希望對大家有所幫助
C# StopWatch 實(shí)現(xiàn)程序精準(zhǔn)計時
下面的示例演示如何使用Stopwatch類來確定應(yīng)用程序的執(zhí)行時間。
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)過時間。 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); // 打印時間差 Console.WriteLine("RunTime " + elapsedTime); } }
Stopwatch還可以來計算性能數(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)對程序運(yùn)行的精確計時
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)計時功能的文章就介紹到這了,更多相關(guān)C# Stopwatch計時內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#導(dǎo)航器Xpath與XPathNavigator類
這篇文章介紹了C#導(dǎo)航器Xpath與XPathNavigator類,文中通過示例代碼介紹的非常詳細(xì)。對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2022-06-06C#程序終極調(diào)試實(shí)現(xiàn)windbg的時間旅行
這篇文章主要介紹了C#程序終極調(diào)試實(shí)現(xiàn)windbg的時間旅行示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06C#導(dǎo)出Excel的幾種常見方式及詳細(xì)實(shí)現(xiàn)步驟
excel導(dǎo)出在C#代碼中應(yīng)用己經(jīng)很廣泛了,我這里就做些總結(jié),下面這篇文章主要給大家介紹了關(guān)于C#導(dǎo)出Excel的幾種常見方式及詳細(xì)實(shí)現(xiàn)步驟的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06使用C#9中records作為強(qiáng)類型ID的實(shí)例教程
這篇文章主要給大家介紹了關(guān)于使用C#9中records作為強(qiáng)類型ID的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01C#與C++之間類型的對應(yīng)知識點(diǎn)總結(jié)
這篇文章主要介紹了C#與C++之間類型的對應(yīng)知識點(diǎn)總結(jié),對此有需要的朋友們可以參考下。2019-08-08