C#使用Stopwatch實(shí)現(xiàn)計(jì)時(shí)功能
前言
在 C# 中,Stopwatch 類(lèi)是用于測(cè)量經(jīng)過(guò)的時(shí)間的工具類(lèi),提供了高精度的計(jì)時(shí)功能。Stopwatch 類(lèi)位于 System.Diagnostics 命名空間中。通常情況下,使用 Stopwatch 的流程是創(chuàng)建一個(gè) Stopwatch 對(duì)象,然后調(diào)用 Start 方法開(kāi)始計(jì)時(shí),執(zhí)行需要測(cè)量時(shí)間的代碼,最后調(diào)用 Stop 方法停止計(jì)時(shí),并通過(guò) Elapsed 屬性獲取經(jīng)過(guò)的時(shí)間。
Stopwatch 類(lèi)中常用的方法包括
Start():開(kāi)始計(jì)時(shí)。
Stop():停止計(jì)時(shí)。
Reset():重置計(jì)時(shí)器。
Restart():重啟計(jì)時(shí)器。
Elapsed:獲取經(jīng)過(guò)的時(shí)間(Elapsed 屬性返回一個(gè) TimeSpan 對(duì)象,表示自 Stopwatch 實(shí)例開(kāi)始計(jì)時(shí)以來(lái)經(jīng)過(guò)的時(shí)間。你可以通過(guò)訪問(wèn) Elapsed 屬性來(lái)獲取經(jīng)過(guò)的時(shí)間)
ElapsedMilliseconds:回一個(gè) long 值,表示自 Stopwatch 實(shí)例開(kāi)始計(jì)時(shí)以來(lái)經(jīng)過(guò)的毫秒數(shù)。
ElapsedTicks:返回一個(gè) long 值,表示自 Stopwatch 實(shí)例開(kāi)始計(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 類(lèi),開(kāi)發(fā)人員可以更準(zhǔn)確地測(cè)量代碼執(zhí)行的時(shí)間,進(jìn)行性能分析和優(yōu)化,從而提升應(yīng)用程序的性能表現(xiàn)。
知識(shí)補(bǔ)充
除了上文的內(nèi)容,小編還為大家整理一些Stopwatch類(lèi)的其他應(yīng)用,希望對(duì)大家有所幫助
C# StopWatch 實(shí)現(xiàn)程序精準(zhǔn)計(jì)時(shí)
下面的示例演示如何使用Stopwatch類(lèi)來(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();
// 開(kāi)始
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)文章
C#導(dǎo)航器Xpath與XPathNavigator類(lèi)
這篇文章介紹了C#導(dǎo)航器Xpath與XPathNavigator類(lèi),文中通過(guò)示例代碼介紹的非常詳細(xì)。對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-06-06
C#程序終極調(diào)試實(shí)現(xiàn)windbg的時(shí)間旅行
這篇文章主要介紹了C#程序終極調(diào)試實(shí)現(xiàn)windbg的時(shí)間旅行示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-06-06
C#導(dǎo)出Excel的幾種常見(jiàn)方式及詳細(xì)實(shí)現(xiàn)步驟
excel導(dǎo)出在C#代碼中應(yīng)用己經(jīng)很廣泛了,我這里就做些總結(jié),下面這篇文章主要給大家介紹了關(guān)于C#導(dǎo)出Excel的幾種常見(jiàn)方式及詳細(xì)實(shí)現(xiàn)步驟的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-06-06
C#比較二個(gè)數(shù)組并找出相同或不同元素的方法
這篇文章主要介紹了C#比較二個(gè)數(shù)組并找出相同或不同元素的方法,涉及C#針對(duì)數(shù)組的交集、補(bǔ)集等集合操作相關(guān)技巧,非常簡(jiǎn)單實(shí)用,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
使用C#9中records作為強(qiáng)類(lèi)型ID的實(shí)例教程
這篇文章主要給大家介紹了關(guān)于使用C#9中records作為強(qiáng)類(lèi)型ID的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01
C#與C++之間類(lèi)型的對(duì)應(yīng)知識(shí)點(diǎn)總結(jié)
這篇文章主要介紹了C#與C++之間類(lèi)型的對(duì)應(yīng)知識(shí)點(diǎn)總結(jié),對(duì)此有需要的朋友們可以參考下。2019-08-08

