C#計算一段程序運行時間的多種方法總結(jié)
直接代碼:
第一種方法利用System.DateTime.Now
static void SubTest()
{
DateTime beforDT = System.DateTime.Now;
//耗時巨大的代碼
DateTime afterDT = System.DateTime.Now;
TimeSpan ts = afterDT.Subtract(beforDT);
Console.WriteLine("DateTime總共花費{0}ms.", ts.TotalMilliseconds);
}第二種用Stopwatch類(System.Diagnostics)
static void SubTest()
{
Stopwatch sw = new Stopwatch();
sw.Start();
//耗時巨大的代碼
sw.Stop();
TimeSpan ts2 = sw.Elapsed;
Console.WriteLine("Stopwatch總共花費{0}ms.", ts2.TotalMilliseconds);
}第三種用API實現(xiàn):
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
static extern bool QueryPerformanceCounter(ref long count);
[System.Runtime.InteropServices.DllImport("Kernel32.dll")]
static extern bool QueryPerformanceFrequency(ref long count);
static void SubTest()
{
long count = 0;
long count1 = 0;
long freq = 0;
double result = 0;
QueryPerformanceFrequency(ref freq);
QueryPerformanceCounter(ref count);
//耗時巨大的代碼
QueryPerformanceCounter(ref count1);
count = count1 - count;
result = (double)(count) / (double)freq;
Console.WriteLine("QueryPerformanceCounter耗時: {0} 秒", result);
}方法補充
C#中獲取程序執(zhí)行時間的三種方法
1. 使用DateTime類
你可以在程序開始執(zhí)行前獲取當前時間,然后在程序結(jié)束時再次獲取當前時間,通過這兩個時間點計算程序執(zhí)行時間。
using System;
class Program
{
static void Main()
{
DateTime startTime = DateTime.Now;
// 執(zhí)行你的代碼
for (int i = 0; i < 1000000; i++)
{
// 示例:一個簡單的循環(huán)
}
DateTime endTime = DateTime.Now;
TimeSpan executionTime = endTime - startTime;
Console.WriteLine("程序執(zhí)行時間: " + executionTime.TotalMilliseconds + " 毫秒");
}
}2. 使用Stopwatch類
System.Diagnostics.Stopwatch類是測量時間的一種更精確的方法,特別是對于需要高精度計時的場景。
using System;
using System.Diagnostics;
class Program
{
static void Main()
{
Stopwatch stopwatch = new Stopwatch();
stopwatch.Start();
// 執(zhí)行你的代碼
for (int i = 0; i < 1000000; i++)
{
// 示例:一個簡單的循環(huán)
}
stopwatch.Stop();
Console.WriteLine("程序執(zhí)行時間: " + stopwatch.ElapsedMilliseconds + " 毫秒");
}
}3. 使用Environment.TickCount或Environment.TickCount64(對于64位系統(tǒng))
這種方法不如Stopwatch精確,但對于簡單的性能測試或快速獲取時間差也是可行的。
using System;
class Program
{
static void Main()
{
int startTime = Environment.TickCount; // 或使用Environment.TickCount64對于64位系統(tǒng)以避免溢出
// 執(zhí)行你的代碼
for (int i = 0; i < 1000000; i++)
{
// 示例:一個簡單的循環(huán)
}
int endTime = Environment.TickCount; // 或使用Environment.TickCount64對于64位系統(tǒng)以避免溢出
int executionTime = endTime - startTime; // 注意:這將返回以毫秒為單位的整數(shù),但不直接提供TimeSpan對象。
Console.WriteLine("程序執(zhí)行時間: " + executionTime + " 毫秒");
}
}到此這篇關于C#計算一段程序運行時間的多種方法總結(jié)的文章就介紹到這了,更多相關C#計算程序運行時間內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
C#實現(xiàn)ProperTyGrid自定義屬性的方法
這篇文章主要介紹了C#實現(xiàn)ProperTyGrid自定義屬性的方法,主要通過接口ICustomTypeDescriptor實現(xiàn),需要的朋友可以參考下2014-09-09
C#中使用DataContractSerializer類實現(xiàn)深拷貝操作示例
這篇文章主要介紹了C#中使用DataContractSerializer類實現(xiàn)深拷貝操作示例,本文給出了實現(xiàn)深拷貝方法、測試深拷貝方法例子、DataContractSerializer類實現(xiàn)深拷貝的原理等內(nèi)容,需要的朋友可以參考下2015-06-06

