国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > C# > 正文

C#計算代碼執行時間的方法

2020-01-24 03:31:38
字體:
來源:轉載
供稿:網友

最近遇到一個模塊其執行時間非常短,但是調用頻率非常高。精確計算其運算時間對于提高程序整體效率來說非常重要。

在我剛剛接觸.Net時,也曾經想要測試一下自己寫的程序的運行時間,當時我使用的是將兩個DateTime.Now相減的笨方法,呵呵。后來知道使用Environment.TickCount,對于一般的測試來說就足夠了。但是它對于高精度測試就沒什么辦法,經常是返回個0了事。對于高精度測試我們應當使用QueryPerformanceFrequency函數和QueryPerformanceCounter函數。通過它們可以獲得比Environment.TickCount更高的精確度。實際上Environment.TickCount就是在調用QueryPerformanceFrequency函數和QueryPerformanceCounter函數。

下面是我使用的代碼:

復制代碼 代碼如下:

using System;

class Class1
{
 [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);

 [STAThread]
 static void Main(string[] args)
 {
 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("耗時: {0} 秒", result);
 Console.ReadLine();
 }
}

這樣能夠得到非常精確的結果。但是模塊每次運行的時間總會有些誤差,而當計算非常精確的時候,這些運行時間的誤差也顯得比較明顯了。為此我對其進行循環多次測試使其誤差平均化,通過多次測試的結果來進行執行效率的分析。

復制代碼 代碼如下:

using System;

class Class1
{
 [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);

 [STAThread]
 static void Main(string[] args)
 {
 long count = 0;
 long count1 = 0;
 long freq = 0;
 double result = 0;

 QueryPerformanceFrequency(ref freq);
 QueryPerformanceCounter(ref count);

 //開始的時候沒有這層循環,所得數據浮動很大,添加這層循環來使得結果更加平均
 for (int i=0; i<500; i++)
 {
 //需要測試的模塊
 }

 QueryPerformanceCounter(ref count1);

 count = count1-count;
 result = (double)(count)/(double)freq;

 Console.WriteLine("耗時: {0} 秒", result);
 Console.ReadLine();
 }
}

C#中的秒表 計算程序運行了多長時間 System.Diagnostics.Stopwatch

復制代碼 代碼如下:

private void button1_Click(object sender, EventArgs e)
{
Stopwatch myWatch = new Stopwatch();
myWatch.Start();
for (int i = 0; i < 1000; i++)
{
Console.WriteLine("just test" + i);
}
myWatch.Stop();
long myUseTime = myWatch.ElapsedMilliseconds;
MessageBox.Show(" 主站蜘蛛池模板: 阿瓦提县| 城口县| 郓城县| 宝兴县| 三亚市| 朝阳市| 嘉黎县| 枣庄市| 大厂| 开化县| 郓城县| 连平县| 三穗县| 珲春市| 诏安县| 罗田县| 新蔡县| 伊金霍洛旗| 皮山县| 红原县| 高碑店市| 和田县| 德惠市| 泸水县| 永胜县| 吴堡县| 佛学| 富川| 楚雄市| 镇赉县| 天台县| 宜都市| 萝北县| 仙游县| 苍梧县| 广德县| 前郭尔| 容城县| 遂昌县| 松溪县| 凤阳县|