C#使用Stopwatch實現(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 實例開始計時以來經(jīng)過的時間。你可以通過訪問 Elapsed 屬性來獲取經(jīng)過的時間)
ElapsedMilliseconds:回一個 long 值,表示自 Stopwatch 實例開始計時以來經(jīng)過的毫秒數(shù)。
ElapsedTicks:返回一個 long 值,表示自 Stopwatch 實例開始計時以來經(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)。
知識補充
除了上文的內(nèi)容,小編還為大家整理一些Stopwatch類的其他應(yīng)用,希望對大家有所幫助
C# StopWatch 實現(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實現(xià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實現(xiàn)計時功能的文章就介紹到這了,更多相關(guān)C# Stopwatch計時內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- C#中高精度計時器Stopwatch的用法詳解
- C#?Stopwatch實現(xiàn)計算代碼運行時間
- C#中Stopwatch的使用及說明
- C# 中使用Stopwatch計時器實現(xiàn)暫停計時繼續(xù)計時功能
- 如何使用C# Stopwatch 測量微秒級精確度
- .NET/C# 使用Stopwatch測量運行時間
- C#使用StopWatch獲取程序毫秒級執(zhí)行時間的方法
- C#中Forms.Timer、Timers.Timer、Threading.Timer的用法分析
- C#中的Timer和DispatcherTimer使用實例
- C#中的三種定時計時器Timer用法介紹
- C#中三種Timer計時器的詳細(xì)用法
- 詳解C#中的定時器Timer類及其垃圾回收機制
- C#使用timer實現(xiàn)的簡單鬧鐘程序
- [C#].NET中幾種Timer的使用實例
- C# 中Stopwatch和timer的實現(xiàn)示例
相關(guān)文章
c#不使用windows api函數(shù)打開我的電腦和獲取電腦驅(qū)動器信息
這篇文章主要介紹了c#不使用windows api函數(shù)打開我的電腦和電腦驅(qū)動器信息的方法,大家參考使用2013-12-12
C# 配置文件app.config 和 web.config詳解
在 C# 的應(yīng)用開發(fā)中,配置文件就像是幕后的大管家,默默管理著應(yīng)用程序的各種設(shè)置,下面通過本文介紹 C# 中極為重要的兩個配置文件,app.config 和 web.config的相關(guān)知識,感興趣的朋友一起看看吧2025-04-04
c#?理解csredis庫實現(xiàn)分布式鎖的詳細(xì)流程
這篇文章主要介紹了c#?理解csredis實現(xiàn)分布式鎖,該庫本身已經(jīng)足夠完善,這里我畫蛇添足一下,為了方便自己的使用,本文通過實例代碼給大家詳細(xì)介紹,需要的朋友可以參考下2022-02-02

