麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 編程 > 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(" 主站蜘蛛池模板: 龙的两根好大拔不出去h | 精品久久久久久久久久久aⅴ | 亚洲精品7777xxxx青睐 | 久久99精品视频在线观看 | 久久久久九九九女人毛片 | a免费视频| 亚洲最新黄色网址 | 91九色视频观看 | 国内自拍网址 | 久久久久久久久久久久久久国产 | 成人一级视频在线观看 | 久久草在线观看视频 | 久久久久久久久久久一区 | 日本视频免费观看 | 欧美女同hd| 黄色免费大片 | 日韩欧美精品电影 | 国产在线地址 | 免费国产一级特黄久久 | 久国久产久精永久网页 | 毛片大全在线观看 | 国产精品热 | 久精品久久 | 国产男女爽爽爽爽爽免费视频 | 欧美大电影免费观看 | 国产乱轮视频 | 九色新网址| 蜜桃av鲁一鲁一鲁一鲁 | 国产羞羞视频在线免费观看 | 黄色网址电影 | 极品xxxx欧美一区二区 | 国产一区二区三区在线观看视频 | 毛片免费视频播放 | 最新国产毛片 | 操毛片 | 亚洲精品一区中文字幕 | 久久精品视频网址 | 主播粉嫩国产在线精品 | 色污视频 | 在线成人亚洲 | 国产午夜亚洲精品午夜鲁丝片 |