C#中獲取程序執(zhí)行時(shí)間的三種方法
在C#中,獲取程序執(zhí)行時(shí)間通常有以下幾種方法:
1. 使用DateTime類
你可以在程序開始執(zhí)行前獲取當(dāng)前時(shí)間,然后在程序結(jié)束時(shí)再次獲取當(dāng)前時(shí)間,通過這兩個(gè)時(shí)間點(diǎn)計(jì)算程序執(zhí)行時(shí)間。
using System;
class Program
{
static void Main()
{
DateTime startTime = DateTime.Now;
// 執(zhí)行你的代碼
for (int i = 0; i < 1000000; i++)
{
// 示例:一個(gè)簡(jiǎn)單的循環(huán)
}
DateTime endTime = DateTime.Now;
TimeSpan executionTime = endTime - startTime;
Console.WriteLine("程序執(zhí)行時(shí)間: " + executionTime.TotalMilliseconds + " 毫秒");
}
}2. 使用Stopwatch類
System.Diagnostics.Stopwatch類是測(cè)量時(shí)間的一種更精確的方法,特別是對(duì)于需要高精度計(jì)時(shí)的場(chǎng)景。
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// 執(zhí)行你的代碼
for (int i = 0; i < 1000000; i++)
{
// 示例:一個(gè)簡(jiǎn)單的循環(huán)
}
stopwatch.Stop();
Console.WriteLine("程序執(zhí)行時(shí)間: " + stopwatch.ElapsedMilliseconds + " 毫秒");
}
}3. 使用Environment.TickCount或Environment.TickCount64(對(duì)于64位系統(tǒng))
這種方法不如Stopwatch精確,但對(duì)于簡(jiǎn)單的性能測(cè)試或快速獲取時(shí)間差也是可行的。
using System;
class Program
{
static void Main()
{
int startTime = Environment.TickCount; // 或使用Environment.TickCount64對(duì)于64位系統(tǒng)以避免溢出
// 執(zhí)行你的代碼
for (int i = 0; i < 1000000; i++)
{
// 示例:一個(gè)簡(jiǎn)單的循環(huán)
}
int endTime = Environment.TickCount; // 或使用Environment.TickCount64對(duì)于64位系統(tǒng)以避免溢出
int executionTime = endTime - startTime; // 注意:這將返回以毫秒為單位的整數(shù),但不直接提供TimeSpan對(duì)象。
Console.WriteLine("程序執(zhí)行時(shí)間: " + executionTime + " 毫秒");
}
}總結(jié):
對(duì)于大多數(shù)應(yīng)用場(chǎng)景,推薦使用Stopwatch類,因?yàn)樗峁┝烁叩木群挽`活性。如果你僅僅需要快速獲取兩個(gè)時(shí)間點(diǎn)之間的差異,并且不介意精度問題,那么使用DateTime類或Environment.TickCount/Environment.TickCount64也是可行的。選擇哪種方法取決于你的具體需求和精度要求。。
以上就是C#中獲取程序執(zhí)行時(shí)間的三種方法的詳細(xì)內(nèi)容,更多關(guān)于C#獲取程序執(zhí)行時(shí)間的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Visual Studio中根據(jù)系統(tǒng)區(qū)分引用64位、32位DLL動(dòng)態(tài)庫(kù)文件的配置方法
這篇文章主要介紹了Visual Studio中根據(jù)系統(tǒng)區(qū)分引用64位、32位DLL動(dòng)態(tài)庫(kù)文件的配置方法,本文在VS2008中測(cè)試通過,其它VS版本可以參考下2014-09-09
Windows窗體的.Net框架繪圖技術(shù)實(shí)現(xiàn)方法
這篇文章主要介紹了Windows窗體的.Net框架繪圖技術(shù)實(shí)現(xiàn)方法,非常實(shí)用,需要的朋友可以參考下2014-08-08

