C#使用Stopwatch實現(xiàn)計時功能
前言
在 C# 中,Stopwatch 類是用于測量經過的時間的工具類,提供了高精度的計時功能。Stopwatch 類位于 System.Diagnostics 命名空間中。通常情況下,使用 Stopwatch 的流程是創(chuàng)建一個 Stopwatch 對象,然后調用 Start 方法開始計時,執(zhí)行需要測量時間的代碼,最后調用 Stop 方法停止計時,并通過 Elapsed 屬性獲取經過的時間。
Stopwatch 類中常用的方法包括
Start():開始計時。
Stop():停止計時。
Reset():重置計時器。
Restart():重啟計時器。
Elapsed:獲取經過的時間(Elapsed 屬性返回一個 TimeSpan 對象,表示自 Stopwatch 實例開始計時以來經過的時間。你可以通過訪問 Elapsed 屬性來獲取經過的時間)
ElapsedMilliseconds:回一個 long 值,表示自 Stopwatch 實例開始計時以來經過的毫秒數(shù)。
ElapsedTicks:返回一個 long 值,表示自 Stopwatch 實例開始計時以來經過的計時周期數(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($"經過的時間: {stopwatch.Elapsed}");
}
}使用總結
通過使用 Stopwatch 類,開發(fā)人員可以更準確地測量代碼執(zhí)行的時間,進行性能分析和優(yōu)化,從而提升應用程序的性能表現(xiàn)。
知識補充
除了上文的內容,小編還為大家整理一些Stopwatch類的其他應用,希望對大家有所幫助
C# StopWatch 實現(xiàn)程序精準計時
下面的示例演示如何使用Stopwatch類來確定應用程序的執(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);
// 結束
stopWatch.Stop();
// 獲取作為 TimeSpan 值的經過時間。
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();
}
}
}到此這篇關于C#使用Stopwatch實現(xiàn)計時功能的文章就介紹到這了,更多相關C# Stopwatch計時內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

